Last active
July 6, 2018 15:14
-
-
Save hdf/836f14b4c0d5c8f6bad202b34ce40112 to your computer and use it in GitHub Desktop.
Extension project for: https://github.com/joshaven/string_score/ adding functionality to find closest matches. See: https://github.com/joshaven/string_score/issues/28
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
// Extension project for: https://github.com/joshaven/string_score/ | |
// See: https://github.com/joshaven/string_score/issues/28 | |
/** | |
* Gives back an array of indexes of the unique closest matches, | |
* on a string array to a string. | |
* 'Hello World'.closest(['el', 'll', 'o', 'll']); //=> [ 0, 1 ] | |
*/ | |
String.prototype.closest = function(words, fuzziness, one2many) { | |
'use strict'; | |
if (!Array.isArray(words) || words.length < 2) return -1; // Wrong usage | |
var results = [], string = this, tmp = [], max = 0, score = 0; | |
var scorer = (!one2many)? // Default is compare many to one | |
function(v){return string.score(v, fuzziness)}: | |
function(v){return v.score(string, fuzziness)}; | |
for (var i = 0; i < words.length; i++) { | |
score = scorer(words[i]); | |
if (max > score) continue; | |
if (!Array.isArray(tmp[score])) tmp[score] = []; | |
tmp[score].push(i); | |
max = score; | |
} | |
// Check if the given word is already present among the results | |
function unique(word) { | |
for (var i = 0; i < results.length; i++) | |
if (words[results[i]] == word) | |
return false; | |
return true; | |
} | |
// Generate results | |
for (var i = 0; i < tmp[max].length; i++) | |
if (unique(words[tmp[max][i]])) | |
results.push(i); | |
return results; | |
}; |
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
String.prototype.closest=function(r,t,n){"use strict";function e(t){for(var n=0;n<u.length;n++)if(r[u[n]]==t)return!1;return!0}if(!Array.isArray(r)||r.length<2)return-1;for(var u=[],o=this,i=[],s=0,f=0,c=n?function(r){return r.score(o,t)}:function(r){return o.score(r,t)},a=0;a<r.length;a++)f=c(r[a]),s>f||(Array.isArray(i[f])||(i[f]=[]),i[f].push(a),s=f);for(var a=0;a<i[s].length;a++)e(r[i[s][a]])&&u.push(a);return u}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment