nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.
57 lines (56 loc) • 1.71 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports._calculateSimilarity = _calculateSimilarity;
exports._buildCharLcsTable = _buildCharLcsTable;
exports._getLcsIndices = _getLcsIndices;
const utilities_1 = require("./utilities");
function _calculateSimilarity(str1, str2) {
if (str1 === str2)
return 1;
const maxLen = Math.max(str1.length, str2.length);
if (maxLen === 0)
return 1;
const distance = (0, utilities_1.getLevenshteinDistance)(str1, str2);
return 1 - distance / maxLen;
}
function _buildCharLcsTable(original, modified) {
const origLen = original.length;
const modLen = modified.length;
const lcs = Array(origLen + 1)
.fill(null)
.map(() => Array(modLen + 1).fill(0));
for (let i = 1; i <= origLen; i++) {
for (let j = 1; j <= modLen; j++) {
if (original[i - 1] === modified[j - 1]) {
lcs[i][j] = lcs[i - 1][j - 1] + 1;
}
else {
lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]);
}
}
}
return lcs;
}
function _getLcsIndices(original, modified, lcs) {
const origLen = original.length;
const modLen = modified.length;
const origMatched = new Set();
const modMatched = new Set();
let i = origLen;
let j = modLen;
while (i > 0 && j > 0) {
if (original[i - 1] === modified[j - 1]) {
origMatched.add(i - 1);
modMatched.add(j - 1);
i--;
j--;
}
else if (lcs[i - 1][j] > lcs[i][j - 1]) {
i--;
}
else {
j--;
}
}
return [origMatched, modMatched];
}