← 中文资源

简体中文版本

子序列模糊匹配打分排序

查询的每个字符必须在目标里按顺序出现,间距越紧得分越高,前缀命中再额外加分:无需任何依赖,就能给命令面板做模糊过滤与结果排序。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

底层就是函数 fuzzyScore。 这里叠了两层循环:for (const char of q) 负责挑选,for (const entry of ranked) 负责处理。 返回值是携带 prefixBonus 的对象。

使用要点

  • 守卫 found === -1 命中后立刻用提前的 return 结束这一轮。
  • 跑完文件,输出里会留下标记——rejected:。

常见问题

fuzzyScore 会修改传入的参数吗?

不会。传入的任何东西都不会被写入,对共享数据调用是安全的。

包管理器会看到什么?

一份空的依赖清单。示例没有需要抓取的导入。 文件在加载时定义 fuzzyScore。

主要签名是 function fuzzyScore(query, target)

核心语句

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 };

代码示例

// 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');