Skip to content

Instantly share code, notes, and snippets.

@phcostabh
Created November 14, 2013 11:34
Show Gist options
  • Select an option

  • Save phcostabh/7465357 to your computer and use it in GitHub Desktop.

Select an option

Save phcostabh/7465357 to your computer and use it in GitHub Desktop.
console.time('matching-words');
var query = 'James Morrison Broken Strings ft. Nelly Furtado',
results = [
'Broken Strings (feat. Nelly Furtado) James Morrison',
'Broken Strings (feat. James Morrison) Nelly Furtado',
],
match, aux = 0, matches;
Array.prototype.unique = function() {
var o = {}, i, l = this.length,
r = [];
for (i = 0; i < l; i += 1) o[this[i]] = this[i];
for (i in o) r.push(o[i]);
return r;
};
String.prototype.ngram = function(n) {
var i, l = this.length - n,
r = [];
for (i = 0; i <= l; i++) {
r.push(this.substring(i + i + n));
}
return r.unique();
};
String.prototype.trigramMatches = function(subject) {
var appearings = 0,
trigram = this.ngram(3),
i,
l = trigram.length;
for (i = 0; i < l; i++) {
if (query.lastIndexOf(trigram[i])) {
appearings++;
}
}
return appearings;
};
for (var i = 0, l = results.length; i < l; i++) {
matches = results[i].trigramMatches(query);
if (matches > aux) {
match = results[i];
aux = matches;
}
}
console.log(match);
console.timeEnd('matching-words');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment