UNPKG

cmpstr

Version:

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

30 lines (27 loc) 899 B
// 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 JaccardIndex extends Metric { constructor(a, b, opt = {}) { super('jaccard', a, b, opt, true); } compute(a, b, m, n) { const [setA, setB] = Pool.acquireMany('set', [m, n]); try { for (const A of a) setA.add(A); for (const B of b) setB.add(B); let intersection = 0; for (const c of setA) if (setB.has(c)) intersection++; const union = setA.size + setB.size - intersection; return { res: union === 0 ? 1 : Metric.clamp(intersection / union), raw: { intersection, union } }; } finally { Pool.release('set', setA, m); Pool.release('set', setB, n); } } } MetricRegistry.add('jaccard', JaccardIndex); export { JaccardIndex };