Fuzzy Subsequence Scoring Ranks Commands

Score subsequence matches by how tightly the query characters cluster inside the target, ranking command palettes without any dependency.

JavascriptCli Tooling

Code

javascriptsnippet
35 lines
// Fuzzy subsequence matching: every query character must appear in the
// target in order; tighter clusters and prefix hits score higher, the way
// editor command palettes rank results
function fuzzyScore(query, target) {
  const q = query.toLowerCase();
  const t = target.toLowerCase();
  let cursor = 0;
  let gap = 0;
  for (const char of q) {
    const found = t.indexOf(char, cursor);
    if (found === -1) return null; // not a subsequence: no match at all
    gap += found - cursor;
    cursor = found + 1;
  }
  const clusterScore = 20 - Math.min(gap, 12);
  const prefixBonus = t.startsWith(q) ? 8 : 0;
  return { score: clusterScore + prefixBonus, gap };
}

const commands = [
  'tab settings',
  'close tab',
  'toggle sidebar',
  'format document',
];

const ranked = commands
  .map((command) => ({ command, match: fuzzyScore('ta', command) }))
  .filter((entry) => entry.match !== null)
  .sort((a, b) => b.match.score - a.match.score);

for (const entry of ranked) {
  console.log(entry.command, '-> score', entry.match.score, 'gap', entry.match.gap);
}
console.log('rejected:', commands.length - ranked.length, 'commands');

Output

Captured from a sandboxed run of this snippet in the build pipeline.

tab settings -> score 28 gap 0
close tab -> score 14 gap 6
toggle sidebar -> score 9 gap 11
rejected: 1 commands

How it works

Fuzzy Subsequence Scoring Ranks Commands reduces to the function fuzzyScore.

Two loops stack here: for (const char of q) selects, for (const entry of ranked) processes.

The result comes back as an object carrying prefixBonus.

Watch out for

  • The guard found === -1 breaks off the flow right there with an early return when its condition holds.

Using it

Entry signature: function fuzzyScore(query, target)

The demo output is labeled (rejected:); each label names the call that printed it.

The call returns prefixBonus.

Key statements

if (found === -1) return null; // not a subsequence: no match at all
gap += found - cursor;
.sort((a, b) => b.match.score - a.match.score);
return { score: clusterScore + prefixBonus, gap };

Interactive Tools for This Topic

FAQ

Does `fuzzyScore` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `fuzzyScore` at load time.