Skip to content

Instantly share code, notes, and snippets.

@padolsey
Last active February 21, 2024 11:49
Show Gist options
  • Save padolsey/a27a32d5859a71403b10 to your computer and use it in GitHub Desktop.
Save padolsey/a27a32d5859a71403b10 to your computer and use it in GitHub Desktop.
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
Copy link

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