Created
August 16, 2022 22:15
-
-
Save GuilhermeRossato/9615bc06c53c4ed0ade487b9ba628a40 to your computer and use it in GitHub Desktop.
Simple javascript function to perform fuzzy search based on sequential characters and return the matching parts
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
/** | |
* Returns a list of index pairs with the sequencial pieces of the query that show up on the parameter | |
* The indexes are between 0 and the text length. | |
* @example query = "hello", text = "ahellow", return = [{startIndex: 1, endIndex: 6}] | |
* @example query = "abc_def", text = "abcdef", return = [{startIndex: 0, endIndex: 3}] | |
* @example query = "abcdef", text = "abc_def", return = [{startIndex: 0, endIndex: 3}, {startIndex: 4, endIndex: 7}] | |
* @example query = "abcd", text = "a b c", return = [{start:0, end:1},{start:2, end:3},{start:4, end:5}] | |
* @params {string} query The search query to transverse the text | |
* @params {string} text The text to find the parts that match the search query | |
*/ | |
function getFuzzySearchMatches(query, text) { | |
/** @type {{startIndex: number, endIndex: number}[]} */ | |
const parts = []; | |
let matchIndex = 0; | |
let obj = {startIndex: -1, endIndex: -1} | |
for (let i = 0; i < text.length && matchIndex < query.length; i++) { | |
//console.log("7", i, JSON.stringify(obj)); | |
if (obj.startIndex === -1) { | |
//console.log("9", i < name.length, {differs: name[i] !== query[matchIndex]}); | |
while (i < text.length && text[i] !== query[matchIndex]) { | |
i++; | |
} | |
//console.log("13", i < name.length, {matches: name[i] === query[matchIndex]}); | |
if (i < text.length && text[i] === query[matchIndex]) { | |
obj.startIndex = i; | |
obj.endIndex = i+1; | |
matchIndex++; | |
parts.push(obj); | |
} | |
} else { | |
//console.log("18", i < name.length, matchIndex < query.length, name[i] === query[matchIndex]); | |
while (i < text.length && matchIndex < query.length && text[i] === query[matchIndex]) { | |
//console.log("20", i < name.length, matchIndex < query.length, name[i] === query[matchIndex]); | |
i++; | |
matchIndex++; | |
} | |
//console.log("24", matchIndex); | |
obj.endIndex = i; | |
obj = {startIndex: -1, endIndex: -1}; | |
} | |
} | |
return parts; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment