Skip to content

Instantly share code, notes, and snippets.

@grapho
Last active May 17, 2018 22:47
Show Gist options
  • Save grapho/4ef4271ce6b17c91c9f65d06719dc096 to your computer and use it in GitHub Desktop.
Save grapho/4ef4271ce6b17c91c9f65d06719dc096 to your computer and use it in GitHub Desktop.
A Fuzzy, Fuzzy Find
/**
* Takes a search term input, and returns a filtered array of results
*/
const getFuzzyFindResults = (searchTerm, array) => {
let segments = searchTerm.split('');
return array.filter(string => {
let matches = segments.reduce((arr, seg, idx) => {
let lcString = string.toLowerCase();
let lcSeg = seg.toLowerCase();
let arrLen = arr.length;
let match;
if (arrLen) {
match = lcString.indexOf(lcSeg, (arr[arrLen - 1] + 1));
} else {
match = lcString.indexOf(lcSeg, arrLen);
}
arr.push(match);
return arr;
}, []);
return matches.every(item => item >= 0);
});
};
const getFuzzyFindResults = (searchTerm, array) => {
let haystack = `/${array.join('/')}/`;
let find = searchTerm.split('').join('\\w*');
let needle = new RegExp('[^\\/]*\\w*' + find + '\\w*[^\\/]*', 'gmi');
return haystack.match(needle);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment