cmpstr
Version:
CmpStr is a lightweight, fast and well performing package for calculating string similarity
35 lines (31 loc) • 1.07 kB
JavaScript
// CmpStr v3.2.2 build-bb61120-260311 by Paul Köhler @komed3 / MIT License
;
var Metric = require('./Metric.cjs');
var Errors = require('../utils/Errors.cjs');
class HammingDistance extends Metric.Metric {
constructor(a, b, opt = {}) {
super('hamming', a, b, opt, true);
}
compute(a, b, m, n, maxLen) {
if (m !== n) {
if (this.options.pad !== undefined) {
if (m < maxLen) a = a.padEnd(maxLen, this.options.pad);
if (n < maxLen) b = b.padEnd(maxLen, this.options.pad);
m = n = maxLen;
} else
throw new Errors.CmpStrUsageError(
`Strings must be of equal length for Hamming Distance, a=${m} and b=${n} given, ` +
`use option.pad for automatic adjustment`,
{ a: m, b: n }
);
}
let dist = 0;
for (let i = 0; i < m; i++) if (a[i] !== b[i]) dist++;
return {
res: m === 0 ? 1 : Metric.Metric.clamp(1 - dist / m),
raw: { dist }
};
}
}
Metric.MetricRegistry.add('hamming', HammingDistance);
exports.HammingDistance = HammingDistance;