Skip to content

Instantly share code, notes, and snippets.

@NotFounds
Created January 29, 2021 06:15
Show Gist options
  • Save NotFounds/56c54fb933977cd4d9c14bb58c7b8f30 to your computer and use it in GitHub Desktop.
Save NotFounds/56c54fb933977cd4d9c14bb58c7b8f30 to your computer and use it in GitHub Desktop.
Simple fuzzy search in TS
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