UNPKG

cmpstr

Version:

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

46 lines (42 loc) 1.42 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 NeedlemanWunschDistance extends Metric.Metric { constructor(a, b, opt = {}) { super('needlemanWunsch', a, b, opt, true); } compute(a, b, m, n, maxLen) { const { match = 1, mismatch = -1, gap = -1 } = this.options; const len = m + 1; const [prev, curr] = Pool.Pool.acquireMany('int32', [len, len]); try { prev[0] = 0; for (let i = 1; i <= m; i++) prev[i] = prev[i - 1] + gap; for (let j = 1; j <= n; j++) { curr[0] = prev[0] + gap; const cb = b.charCodeAt(j - 1); for (let i = 1; i <= m; i++) { const score = a.charCodeAt(i - 1) === cb ? match : mismatch; curr[i] = Math.max( prev[i - 1] + score, prev[i] + gap, curr[i - 1] + gap ); } prev.set(curr); } const score = prev[m]; const denum = maxLen * match; return { res: denum === 0 ? 0 : Metric.Metric.clamp(score / denum), raw: { score, denum } }; } finally { Pool.Pool.release('int32', prev, len); Pool.Pool.release('int32', curr, len); } } } Metric.MetricRegistry.add('needlemanWunsch', NeedlemanWunschDistance); exports.NeedlemanWunschDistance = NeedlemanWunschDistance;