Skip to content

Instantly share code, notes, and snippets.

@DevinClark
Last active December 13, 2021 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DevinClark/311b09c1d1dcf0a2b2edd321162d4d8b to your computer and use it in GitHub Desktop.
Save DevinClark/311b09c1d1dcf0a2b2edd321162d4d8b to your computer and use it in GitHub Desktop.
Simple fuzzy searching algorithm
/**
* 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