Last active
December 18, 2015 19:39
-
-
Save dom111/5834793 to your computer and use it in GitHub Desktop.
A (slightly better than the last) go at implementing fuzzy matching in a similar way to the Sublime Text command palette.
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() { | |
var z = function(a, s, k){ | |
var a = a.concat(), // copy array | |
r = [], // create empty array | |
v,m,l, // containers | |
e = RegExp('^.*?' + (s.split('').join('.*?')), 'i'); // build fuzzy RE | |
// iterate all elements | |
while (l = a.pop()) { | |
// if we have a key specified, use that | |
v = k && l.k || l; | |
// perform the match | |
m = v.match(e); | |
if (m) { | |
r.push({ | |
v: l, | |
s: m[0].length // score | |
}); | |
} | |
} | |
// sort by shortest match first | |
r.sort(function(a, b) { | |
return a.s < b.s ? -1 : a.s > b.s ? 1 : 0 | |
}); | |
// remove the scores | |
while (l = r.shift()){ | |
a.push(l.v); | |
} | |
return a; | |
}; | |
// z=function(a,s,k){a=a.concat(),r=[],e=RegExp('^.*?'+s.split('').join('.*?'),'i');while(l=a.pop())v=k?l.k:l,m=v.match(e),m&&r.push({v:l,s:m[0].length});r.sort(function(a,b){return a.s<b.s?-1:a.s>b.s?1:0});while(l=r.shift())a.push(l.v);return a} | |
//console.log(z(['SublimeText2','Sublimation','SublMate','TextMate'], 'sublmt')); // returns: ['SublMate', 'Sublimation', 'SublimeText2'] | |
//console.log(z(['SublimeText2','Sublimation','SublMate','TextMate'], 'text')); // returns: ['TextMate', 'SublimeText2'] | |
String.prototype.fuzzyMatch = function(s) { | |
var e = RegExp('^.*?' + (s.split('').join('.*?')), 'i'); // build fuzzy RE | |
return !!this.match(e); | |
} | |
Array.prototype.fuzzyFilter = function(s, k) { | |
z(this, s, k); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment