logigate/app/lib/match.ts

18 lines
590 B
TypeScript

// How well a name matches what was typed, for finding parts by keyboard.
/**
* The whole name, its start, a word start, anywhere in it, or its letters
* in order (adr4 finds Adder 4); 0 for no match. Empty input matches all.
*/
export function matchScore(text: string, q: string): number {
const t = text.toLowerCase()
if (!q) return 1
if (t === q) return 100
if (t.startsWith(q)) return 80
if (t.split(/[\s\-_/()]+/).some(w => w.startsWith(q))) return 60
if (t.includes(q)) return 40
let i = 0
for (const c of t) if (c === q[i]) i++
return i === q.length ? 15 : 0
}