-
-
Save mattbontrager/cc89f9ef7d6e8309725c9cd2e43da604 to your computer and use it in GitHub Desktop.
This file contains 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
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') | |
]); |
This file contains 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
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' | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment