UNPKG

cmpstr

Version:

CmpStr is a lightweight, fast and well performing package for calculating string similarity

48 lines (45 loc) 1.48 kB
// CmpStr v3.2.2 build-bb61120-260311 by Paul Köhler @komed3 / MIT License import { Pool } from '../utils/Pool.mjs'; import { MetricRegistry, Metric } from './Metric.mjs'; class DamerauLevenshteinDistance extends Metric { constructor(a, b, opt = {}) { super('damerau', a, b, opt, true); } compute(a, b, m, n, maxLen) { const len = m + 1; const [test, prev, curr] = Pool.acquireMany('int32', [len, len, len]); try { for (let i = 0; i <= m; i++) prev[i] = i; for (let j = 1; j <= n; j++) { curr[0] = j; const cb = b.charCodeAt(j - 1); for (let i = 1; i <= m; i++) { const ca = a.charCodeAt(i - 1); const cost = ca === cb ? 0 : 1; let val = Math.min(curr[i - 1] + 1, prev[i] + 1, prev[i - 1] + cost); if ( i > 1 && j > 1 && ca === b.charCodeAt(j - 2) && cb === a.charCodeAt(i - 2) ) val = Math.min(val, test[i - 2] + cost); curr[i] = val; } test.set(prev); prev.set(curr); } const dist = prev[m]; return { res: maxLen === 0 ? 1 : Metric.clamp(1 - dist / maxLen), raw: { dist, maxLen } }; } finally { Pool.release('int32', test, len); Pool.release('int32', prev, len); Pool.release('int32', curr, len); } } } MetricRegistry.add('damerau', DamerauLevenshteinDistance); export { DamerauLevenshteinDistance };