igoist
2021-05-11 18:38:48 +08:00
我抛砖引玉下吧,有兴趣的可以自己加参数去做精度的设置、优化:
(() => {
const fuzzyMatches = (fuzzy, text) => {
fuzzy = fuzzy.toLowerCase();
text = text.toLowerCase();
let tp = 0; // text position / pointer
let matches = [];
// 这边随你去优化
for (let i = 0; i < fuzzy.length; i++) {
const f = fuzzy[i];
for (; tp < text.length; tp++) {
const t = text[tp];
if (f === t) {
matches.push(tp);
tp++;
break;
}
}
}
return matches;
};
// let r = fuzzyMatches('路边有一条狗', '路边有一只狗'); // r = [ 0, 1, 2, 3 ]
// let r = fuzzyMatches('路边有一条狗', '路边有一只小狗'); // r = [ 0, 1, 2, 3 ]
// let r = fuzzyMatches('路边有一条狗', '路边有一只小花狗'); // r = [ 0, 1, 2, 3 ]
let r = fuzzyMatches('路边有一条狗', '道路旁边有一只小狗'); // r = [ 1, 3, 4, 5 ]
console.log(r);
})();