Skip to content

Instantly share code, notes, and snippets.

@jashkenas
Created April 3, 2010 21:37

Revisions

  1. jashkenas created this gist Apr 3, 2010.
    41 changes: 41 additions & 0 deletions quicksilver.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    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
    44 changes: 44 additions & 0 deletions quicksilver.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    (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;
    };
    })();