1
0
mirror of https://github.com/robonen/tools.git synced 2026-03-20 10:54:44 +00:00

refactor(packages/stdlib): rename arguments to left and right

This commit is contained in:
2024-04-11 21:16:53 +07:00
parent 92721b348a
commit 7d8f5be6e9

View File

@@ -1,37 +1,37 @@
/**
* Calculate the Levenshtein distance between two strings
*
* @param {string} a First string
* @param {string} b Second string
* @param {string} left First string
* @param {string} right Second string
* @returns {number} The Levenshtein distance between the two strings
*/
export function levenshteinDistance(a: string, b: string): number {
export function levenshteinDistance(left: string, right: string): number {
// If the strings are equal, the distance is 0
if (a === b) return 0;
if (left === right) return 0;
// If either string is empty, the distance is the length of the other string
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
if (left.length === 0) return right.length;
if (right.length === 0) return left.length;
// Create empty edit distance matrix for all possible modifications of
// substrings of a to substrings of b
const distanceMatrix = Array(b.length + 1).fill(null).map(() => Array(a.length + 1).fill(null));
// substrings of left to substrings of right
const distanceMatrix = Array(right.length + 1).fill(null).map(() => Array(left.length + 1).fill(null));
// Fill the first row of the matrix
// If this is the first row, we're transforming from an empty string to a
// In this case, the number of operations equals the length of a substring
for (let i = 0; i <= a.length; i++)
// If this is the first row, we're transforming from an empty string to left
// In this case, the number of operations equals the length of left substring
for (let i = 0; i <= left.length; i++)
distanceMatrix[0]![i]! = i;
// Fill the first column of the matrix
// If this is the first column, we're transforming empty string to b
// In this case, the number of operations equals the length of b substring
for (let j = 0; j <= b.length; j++)
// If this is the first column, we're transforming empty string to right
// In this case, the number of operations equals the length of right substring
for (let j = 0; j <= right.length; j++)
distanceMatrix[j]![0]! = j;
for (let j = 1; j <= b.length; j++) {
for (let i = 1; i <= a.length; i++) {
const indicator = a[i - 1] === b[j - 1] ? 0 : 1;
for (let j = 1; j <= right.length; j++) {
for (let i = 1; i <= left.length; i++) {
const indicator = left[i - 1] === right[j - 1] ? 0 : 1;
distanceMatrix[j]![i]! = Math.min(
distanceMatrix[j]![i - 1]! + 1, // deletion
distanceMatrix[j - 1]![i]! + 1, // insertion
@@ -40,5 +40,5 @@ export function levenshteinDistance(a: string, b: string): number {
}
}
return distanceMatrix[b.length]![a.length]!;
return distanceMatrix[right.length]![left.length]!;
}