Skip to content

Instantly share code, notes, and snippets.

@jashkenas
Created April 3, 2010 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jashkenas/354868 to your computer and use it in GitHub Desktop.
Save jashkenas/354868 to your computer and use it in GitHub Desktop.
cdoc.string.quicksilver: (string, abbreviation, offset) ->
offset: or 0
len: abbreviation.length
return 0.9 if len is 0
return 0.0 if len > string.length
for i in [len...0]
sub_abbreviation: abbreviation.substring 0, i
index: string.indexOf sub_abbreviation
continue if index < 0 or (index + len > string.length + offset)
next_string: string.substring index + sub_abbreviation.length
if i >= len
next_abbreviation: ''
else
next_abbreviation: abbreviation.substring i
remaining_score: cdoc.string.quicksilver next_string, next_abbreviation, offset + index
continue if remaining_score <= 0
score: string.length - next_string.length
if index isnt 0
c: string.charCodeAt index - 1
if c is 32 or c is 9
for j in [(index - 2)..0]
c: string.charCodeAt j
score: - (if c is 32 or c is 9 then 1 else 0.15)
else
score: - index
score: + remaining_score * next_string.length
score: / string.length
return score
return 0.0
(function(){
cdoc.string.quicksilver = function quicksilver(string, abbreviation, offset) {
var _a, _b, _c, _d, _e, _f, c, i, index, j, len, next_abbreviation, next_string, remaining_score, score, sub_abbreviation;
offset = offset || 0;
len = abbreviation.length;
if (len === 0) {
return 0.9;
}
if (len > string.length) {
return 0.0;
}
_b = len; _c = 0;
for (_a = 0, i = _b; (_b <= _c ? i < _c : i > _c); (_b <= _c ? i += 1 : i -= 1), _a++) {
sub_abbreviation = abbreviation.substring(0, i);
index = string.indexOf(sub_abbreviation);
if (index < 0 || (index + len > string.length + offset)) {
continue;
}
next_string = string.substring(index + sub_abbreviation.length);
i >= len ? (next_abbreviation = '') : (next_abbreviation = abbreviation.substring(i));
remaining_score = cdoc.string.quicksilver(next_string, next_abbreviation, offset + index);
if (remaining_score <= 0) {
continue;
}
score = string.length - next_string.length;
if (index !== 0) {
c = string.charCodeAt(index - 1);
if (c === 32 || c === 9) {
_e = (index - 2); _f = 0;
for (_d = 0, j = _e; (_e <= _f ? j <= _f : j >= _f); (_e <= _f ? j += 1 : j -= 1), _d++) {
c = string.charCodeAt(j);
score -= (c === 32 || c === 9 ? 1 : 0.15);
}
} else {
score -= index;
}
}
score += remaining_score * next_string.length;
score /= string.length;
return score;
}
return 0.0;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment