UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

36 lines (35 loc) • 1.13 kB
export function editDistance(a, b) { if (a === b) return 0; const m = a.length; const n = b.length; const d = Array.from({ length: m + 1 }, (_, i) => Array.from({ length: n + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0))); for (let i = 1; i <= m; i++) { for (let j = 1; j <= n; j++) { const cost = a[i - 1] === b[j - 1] ? 0 : 1; d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1); } } } return d[m][n]; } export function closestName(query, candidates) { let best; let bestDist = 3; const seen = new Set(); for (const c of candidates) { if (seen.has(c)) continue; seen.add(c); if (Math.abs(c.length - query.length) > 2) continue; const dist = editDistance(query, c); if (dist <= 2 && dist < bestDist) { bestDist = dist; best = c; } } return best; }