trellis
Version:
Agentic State Engine — event-sourced causal graph with branching, decision traces, and realtime sync for AI-native applications
57 lines (55 loc) • 1.32 kB
JavaScript
// src/headless/fuzzy.ts
function fuzzyScore(query, target) {
if (query === "") return 1;
const q = query.toLowerCase();
const t = target.toLowerCase();
if (q === t) return 1e3;
let score = 0;
let lastIndex = -1;
let run = 0;
for (const char of q) {
const idx = t.indexOf(char, lastIndex + 1);
if (idx === -1) return 0;
run = idx === lastIndex + 1 ? run + 1 : 0;
score += 1 + run * 2 - (idx - lastIndex - 1);
lastIndex = idx;
}
if (t.startsWith(q)) score += 10;
return Math.max(1, score);
}
function fuzzyMatch(query, text) {
let best = 0;
for (const t of text) {
const s = fuzzyScore(query, t);
if (s > best) best = s;
}
return best;
}
function fuzzyRanges(query, target) {
if (query === "") return [];
const q = query.toLowerCase();
const t = target.toLowerCase();
const indices = [];
let lastIndex = -1;
for (const char of q) {
const idx = t.indexOf(char, lastIndex + 1);
if (idx === -1) return [];
indices.push(idx);
lastIndex = idx;
}
const ranges = [];
for (const idx of indices) {
const last = ranges[ranges.length - 1];
if (last && idx === last[1]) {
last[1] = idx + 1;
} else {
ranges.push([idx, idx + 1]);
}
}
return ranges;
}
export {
fuzzyScore,
fuzzyMatch,
fuzzyRanges
};