UNPKG

cmpstr

Version:

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

39 lines (35 loc) 1.11 kB
// 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 LCSMetric extends Metric.Metric { constructor(a, b, opt = {}) { super('lcs', a, b, opt, true); } compute(a, b, m, n, maxLen) { const len = m + 1; const [prev, curr] = Pool.Pool.acquireMany('int32', [len, len]); try { for (let i = 0; i <= m; i++) prev[i] = 0; for (let j = 1; j <= n; j++) { curr[0] = 0; const cb = b.charCodeAt(j - 1); for (let i = 1; i <= m; i++) { if (a.charCodeAt(i - 1) === cb) curr[i] = prev[i - 1] + 1; else curr[i] = Math.max(prev[i], curr[i - 1]); } prev.set(curr); } const lcs = prev[m]; return { res: maxLen === 0 ? 1 : Metric.Metric.clamp(lcs / maxLen), raw: { lcs, maxLen } }; } finally { Pool.Pool.release('int32', prev, len); Pool.Pool.release('int32', curr, len); } } } Metric.MetricRegistry.add('lcs', LCSMetric); exports.LCSMetric = LCSMetric;