实现说明
底层就是函数 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');