Avoid doing stridx twice

This commit is contained in:
2025-09-15 01:19:21 -04:00
parent 7b8f3f7a5e
commit 8b5cdee1c0

23
lc.vim
View File

@@ -5,26 +5,29 @@ class Item
const val: string const val: string
endclass endclass
def GetLongestSuffix(hay: string, ndl: string): string def GetLongestSuffix(hay: string, ndl: string): tuple<string, number>
var s = ndl var s = ndl
var l = len(ndl) var l = len(ndl)
while stridx(hay, s) == -1 while true
s = strpart(s, 1) const idx = stridx(hay, s)
if idx != -1
return (s, idx)
endif
l = l - 1 l = l - 1
if l == 0 if l == 0
return "" break
endif endif
s = strpart(s, 1)
endwhile endwhile
return s return ("", 0)
enddef enddef
# echo GetLongestSuffix("hello world", "world")->assert_equal("world") # echo GetLongestSuffix("hello world", "world")->assert_equal(("world", 6))
# echo GetLongestSuffix("hello world", "foo world")->assert_equal("o world") # echo GetLongestSuffix("hello world", "foo world")->assert_equal(("o world", 4))
# echo GetLongestSuffix("hello world foo bar blah", "foo world")->assert_equal("o world") # echo GetLongestSuffix("hello world foo bar blah", "foo world")->assert_equal(("o world", 4))
# echo v:errors # echo v:errors
def GetMatch(base: string, line: string): Item def GetMatch(base: string, line: string): Item
const s = GetLongestSuffix(line, base) const [s, idx] = GetLongestSuffix(line, base)
const idx = stridx(line, s)
const slen = strlen(s) const slen = strlen(s)
const m = strpart(line, idx + slen) const m = strpart(line, idx + slen)
return Item.new(slen, base .. m) return Item.new(slen, base .. m)