Instantly share code, notes, and snippets.

Embed
What would you like to do?
var uk = createFuzzyScorer('United Kingdom');
var us = createFuzzyScorer('United States');
console.log([
uk('United') > uk('uk'),
uk('nited') > uk('ingdom'),
uk('united kingdom') > uk('united kingdo'),
uk('united dom') < uk('united kin'),
uk('knited k') > uk('dom'),
uk('_united_') < uk('united'),
uk('United') == us('United')
]);
function createFuzzyScorer(text) {
var UNIVERSAL_MAX = 1e9;
var matcher = makeFuzzyRegex(text);
return function(query) {
var match = matcher.exec(query);
if (!match) return 0;
var captures = match.slice(1);
var score = 0; console.log(captures);
for (var i = 0, l = captures.length; i < l; i += 3) {
var relevancyOfCharacter = Math.pow(i + 1, -2);
if (captures[i]) score -= relevancyOfCharacter * 0.1;
if (captures[i+1]) score += relevancyOfCharacter * 1;
if (captures[i+2]) score -= relevancyOfCharacter * 0.1;
}
return score;
};
function makeFuzzyRegex(string) {
if (!string) { return /^$/; }
// Escape any potential special characters:
var cleansed = string.replace(/\W/g, '\\$&');
return RegExp(
'^' +
cleansed.replace(
// Find every escaped and non-escaped char:
/(\\?.)/g,
// Replace with fuzzy character matcher:
'(?:(^.)?($1)(.??))?'
) +
'$',
'i'
);
}
}
@michacom

This comment has been minimized.

michacom commented Jul 21, 2015

may it be better, if you code w/o slice and start the for from 1, at makeFuzzyRegex function?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment