UNPKG

string-metric

Version:

Get string similarity in JavaScript or TypeScript

48 lines (47 loc) 1.81 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.LongestCommonSubsequence = void 0; var utils_1 = require("./utils/utils"); var LongestCommonSubsequence = /** @class */ (function () { function LongestCommonSubsequence() { } LongestCommonSubsequence.prototype.distance = function (s1, s2) { if (utils_1.isNullOrUndefined(s1)) { throw new Error('s1 must neither be null nor undefined'); } if (utils_1.isNullOrUndefined(s2)) { throw new Error('s2 must neither be null nor undefined'); } if (s1 === s2) { return 0; } return s1.length + s2.length - 2 * this.length(s1, s2); }; LongestCommonSubsequence.prototype.length = function (s1, s2) { if (utils_1.isNullOrUndefined(s1)) { throw new Error('s1 must neither be null nor undefined'); } if (utils_1.isNullOrUndefined(s2)) { throw new Error('s2 must neither be null nor undefined'); } var s1_length = s1.length; var s2_length = s2.length; var x = s1; var y = s2; var c = utils_1.createTwoDimensionalArray(s1_length + 1, s2_length + 1); utils_1.fillTwoDimensionalArray(c); for (var i = 1; i <= s1_length; i++) { for (var j = 1; j <= s2_length; j++) { if (x[i - 1] === y[j - 1]) { c[i][j] = c[i - 1][j - 1] + 1; } else { c[i][j] = Math.max(c[i][j - 1], c[i - 1][j]); } } } return c[s1_length][s2_length]; }; return LongestCommonSubsequence; }()); exports.LongestCommonSubsequence = LongestCommonSubsequence;