Skip to content

Instantly share code, notes, and snippets.

@arielsalminen
Created November 3, 2014 18:23
Show Gist options
  • Save arielsalminen/8c2b8a5da8e8eeb8e5f5 to your computer and use it in GitHub Desktop.
Save arielsalminen/8c2b8a5da8e8eeb8e5f5 to your computer and use it in GitHub Desktop.
/*!
* Upstatic string ranking algorithm v1.0
* (A port of the Quicksilver string ranking algorithm)
*
* http://upstatic.io
*/
String.prototype.score = function (abbreviation) {
if (abbreviation.length === 0) return 0.9;
if (abbreviation.length > this.length) return 0.0;
for (var i = abbreviation.length; i > 0; i--) {
var sub_abbreviation = abbreviation.substring(0,i);
var index = this.indexOf(sub_abbreviation);
if (index < 0) continue;
if (index + abbreviation.length > this.length) continue;
var next_string = this.substring(index + sub_abbreviation.length);
var next_abbreviation = null;
if (i >= abbreviation.length) {
next_abbreviation = "";
} else {
next_abbreviation = abbreviation.substring(i);
}
var remaining_score = next_string.score(next_abbreviation, index);
if (remaining_score > 0) {
var score = this.length - next_string.length;
if (index != 0) {
var j = 0;
var char = this.charCodeAt(index - 1);
if (char === 32 || char === 9) {
for (var j = (index - 2); j >= 0; j--) {
char = this.charCodeAt(j);
score -= ((char === 32 || char === 9) ? 1 : 0.15);
}
} else {
score -= index;
}
}
score += remaining_score * next_string.length;
score /= this.length;
return score;
}
}
return 0.0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment