Skip to content

Instantly share code, notes, and snippets.

@tvararu
Last active February 18, 2017 09:08
Show Gist options
  • Save tvararu/279769e375d13d31c2c0c58b180d3192 to your computer and use it in GitHub Desktop.
Save tvararu/279769e375d13d31c2c0c58b180d3192 to your computer and use it in GitHub Desktop.
function fuzzysearch (needle, haystack) {
var hlen = haystack.length
var nlen = needle.length
if (nlen > hlen) {
return false
}
if (nlen === hlen) {
return needle === haystack
}
outer: for (var i = 0, j = 0; i < nlen; i++) {
var nch = needle.charCodeAt(i)
while (j < hlen) {
if (haystack.charCodeAt(j++) === nch) {
continue outer
}
}
return false
}
return true
}
function fuzzysearch2 (needle, haystack) {
var haystackArray = Array.from(haystack)
var needleArray = Array.from(needle)
if (needleArray.length > haystackArray.length) {
return false
}
if (needleArray.length === haystackArray.length) {
return needle === haystack // Not unicode friendly.
}
var haystackSymbol = haystackArray.shift()
var foundNeedle = needleArray.reduce((acc, needleSymbol) => {
while (haystackSymbol && haystackSymbol !== needleSymbol) { // Not unicode friendly.
haystackSymbol = haystackArray.shift()
}
if (haystackSymbol === needleSymbol) { // Not unicode friendly.
acc += needleSymbol
}
return acc
}, '')
return needle === foundNeedle
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment