cmpstr
Version:
CmpStr is a lightweight, fast and well performing package for calculating string similarity
47 lines (43 loc) • 1.44 kB
JavaScript
// CmpStr v3.2.2 build-bb61120-260311 by Paul Köhler @komed3 / MIT License
;
var Pool = require('../utils/Pool.cjs');
var Metric = require('./Metric.cjs');
class SmithWatermanDistance extends Metric.Metric {
constructor(a, b, opt = {}) {
super('smithWaterman', a, b, opt, true);
}
compute(a, b, m, n) {
const { match = 2, mismatch = -1, gap = -2 } = this.options;
const len = m + 1;
const [prev, curr] = Pool.Pool.acquireMany('int32', [len, len]);
let maxScore = 0;
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++) {
const score = a.charCodeAt(i - 1) === cb ? match : mismatch;
curr[i] = Math.max(
0,
prev[i - 1] + score,
prev[i] + gap,
curr[i - 1] + gap
);
if (curr[i] > maxScore) maxScore = curr[i];
}
prev.set(curr);
}
const denum = Math.min(m * match, n * match);
return {
res: denum === 0 ? 0 : Metric.Metric.clamp(maxScore / denum),
raw: { score: maxScore, denum }
};
} finally {
Pool.Pool.release('int32', prev, len);
Pool.Pool.release('int32', curr, len);
}
}
}
Metric.MetricRegistry.add('smithWaterman', SmithWatermanDistance);
exports.SmithWatermanDistance = SmithWatermanDistance;