UNPKG

cmpstr

Version:

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

32 lines (28 loc) 944 B
// CmpStr v3.2.2 build-bb61120-260311 by Paul Köhler @komed3 / MIT License 'use strict'; var Pool = require('../utils/Pool.cjs'); var Metric = require('./Metric.cjs'); class JaccardIndex extends Metric.Metric { constructor(a, b, opt = {}) { super('jaccard', a, b, opt, true); } compute(a, b, m, n) { const [setA, setB] = Pool.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.Metric.clamp(intersection / union), raw: { intersection, union } }; } finally { Pool.Pool.release('set', setA, m); Pool.Pool.release('set', setB, n); } } } Metric.MetricRegistry.add('jaccard', JaccardIndex); exports.JaccardIndex = JaccardIndex;