UNPKG

cmpstr

Version:

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

37 lines (34 loc) 1.09 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 DiceSorensenCoefficient extends Metric { constructor(a, b, opt = {}) { super('dice', a, b, opt, true); } _bigrams(str) { const len = str.length - 1; const bigrams = Pool.acquire('set', len); for (let i = 0; i < len; i++) bigrams.add(str.substring(i, i + 2)); return bigrams; } compute(a, b) { const setA = this._bigrams(a), setB = this._bigrams(b); const sizeA = setA.size, sizeB = setB.size; try { let intersection = 0; for (const bigram of setA) if (setB.has(bigram)) intersection++; const size = sizeA + sizeB; return { res: size === 0 ? 1 : Metric.clamp((2 * intersection) / size), raw: { intersection, size } }; } finally { Pool.release('set', setA, sizeA); Pool.release('set', setB, sizeB); } } } MetricRegistry.add('dice', DiceSorensenCoefficient); export { DiceSorensenCoefficient };