Last active
February 21, 2024 11:49
-
-
Save padolsey/a27a32d5859a71403b10 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
may it be better, if you code w/o
slice
and start thefor
from 1, atmakeFuzzyRegex
function?