Created
January 29, 2021 06:15
-
-
Save NotFounds/56c54fb933977cd4d9c14bb58c7b8f30 to your computer and use it in GitHub Desktop.
Simple fuzzy search in TS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function fuzzySearch(source: string, query: string, isIgnoreCase?: boolean): boolean { | |
if (source.length === 0 || query.length === 0) { | |
return false; | |
} | |
const _source = isIgnoreCase ? source.toLowerCase() : source; | |
const _query = isIgnoreCase ? query.toLowerCase() : query; | |
const queryIterator = function*() { | |
yield* [..._query]; | |
}; | |
const itr = queryIterator(); | |
let cur = itr.next(); | |
for (const c of _source) { | |
if (c === cur.value) { | |
cur = itr.next(); | |
} | |
if (cur.done) { | |
return true; | |
} | |
} | |
return false; | |
} | |
function test(source: string, query: string, expected: boolean) { | |
const got = fuzzySearch(source, query); | |
console.log(`fuzzySearch("${source}", "${query}")`); | |
console.log(` got: ${got}`); | |
console.log(` expected: ${expected}`); | |
} | |
test("FooBarBaz", "FBB", true); | |
test("FooBarBaz", "ar", true); | |
test("FooBarBaz", "Baz", true); | |
test("FooBarBaz", "z", true); | |
test("FooBarBaz", "FooBarBaz", true); | |
test("FooBarBaz", "ooaraz", true); | |
test("FooBarBaz", "hoge", false); | |
test("FooBarBaz", "", false); | |
test("Foo", "FooBarBaz", false); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment