Last active
December 13, 2021 17:20
-
-
Save DevinClark/311b09c1d1dcf0a2b2edd321162d4d8b to your computer and use it in GitHub Desktop.
Simple fuzzy searching algorithm
This file contains hidden or 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
/** | |
* A fuzzy match algorithm. | |
* @param {string} needle the string to search for | |
* @param {string} haystack the string to search in | |
*/ | |
export function fuzzyMatch(needle: string = "", haystack: string = "") { | |
const haystackLen = haystack.length; | |
const needleLength = needle.length; | |
needle = needle.toLowerCase(); | |
haystack = haystack.toLowerCase(); | |
// needle is too long to contain haystack | |
if (needleLength > haystackLen) { | |
return false; | |
} | |
// needle is either haystack or not a match. | |
if (needleLength === haystackLen) { | |
return needle === haystack; | |
} | |
return needle.split("").every(function (n) { | |
const needleChar = n.charCodeAt(0); | |
let j = 0; | |
while (j < haystackLen) { | |
if (haystack.charCodeAt(j++) === needleChar) { | |
return true; | |
} | |
} | |
return false; | |
}); | |
} | |
/** | |
* Fuzzy searching an array of fields. | |
*/ | |
export function fuzzySearch<Field extends Object>(fields: Field[], searchableFields: Array<keyof Partial<Field>> = []) { | |
const fieldsIndex = fields.map((field) => { | |
var fieldIndex = ""; | |
for (let i = 0; i < searchableFields.length; i++) { | |
let fieldKey = searchableFields[i]; | |
if (typeof field[fieldKey] === "string") { | |
fieldIndex += `${field[fieldKey]}|`; | |
} | |
} | |
return fieldIndex; | |
}); | |
return function search(search: string): Field[] { | |
let searchResults = []; | |
for (let i = 0; i < fieldsIndex.length; i++) { | |
if (fuzzyMatch(search, fieldsIndex[i])) { | |
searchResults.push(fields[i]); | |
} | |
} | |
return searchResults; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment