entropyx
Version:
A simple data mining library, written in TypeScript
54 lines • 1.87 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.Distance = void 0;
class Distance {
static squaredEuclidean(a, b) {
if (a.length !== b.length) {
throw new Error('Points must have the same dimension');
}
let sum = 0;
for (let i = 0; i < a.length; i++) {
const diff = a[i] - b[i];
sum += diff * diff;
}
return sum;
}
static euclidean(a, b) {
return Math.sqrt(Distance.squaredEuclidean(a, b));
}
static manhattan(a, b) {
if (a.length !== b.length) {
throw new Error('Points must have the same dimension');
}
let total = 0;
for (let i = 0; i < a.length; i++) {
total += Math.abs(a[i] - b[i]);
}
return total;
}
static levenshtein(first, second, options = {}) {
const deletionCost = options.deletionCost ?? 1;
const insertionCost = options.insertionCost ?? 1;
const substitutionCost = options.substitutionCost ?? 1;
const cache = new Map();
function lev(i, j) {
if (i <= 0)
return j * insertionCost;
if (j <= 0)
return i * deletionCost;
const key = `${i}:${j}`;
if (cache.has(key)) {
return cache.get(key) || 0;
}
const costDel = lev(i - 1, j) + deletionCost;
const costIns = lev(i, j - 1) + insertionCost;
const costSub = lev(i - 1, j - 1) + (first[i - 1] === second[j - 1] ? 0 : substitutionCost);
const minCost = Math.min(costDel, costIns, costSub);
cache.set(key, minCost);
return minCost;
}
return lev(first.length, second.length);
}
}
exports.Distance = Distance;
//# sourceMappingURL=distance.js.map
;