From 8a387534133f9c104cafe1330955328440afcc7d Mon Sep 17 00:00:00 2001 From: Peery Date: Sun, 15 Oct 2017 16:24:07 +0200 Subject: [PATCH] Added commands.js and editDistance function Created commands.js for command related functions. Also added edit distance calculation for error correction. --- commands.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 commands.js diff --git a/commands.js b/commands.js new file mode 100644 index 0000000..0832314 --- /dev/null +++ b/commands.js @@ -0,0 +1,34 @@ +// Compute the edit distance between the two given strings +function getEditDistance(sourceString, targetString) { + if (sourceString.length === 0) return targetString.length; + if (targetString.length === 0) return sourceString.length; + + let matrix = []; + + // increment along the first column of each row + for (let i = 0; i <= targetString.length; i++) { + matrix[i] = [i]; + } + + // increment each column in the first row + for (let j = 0; j <= sourceString.length; j++) { + matrix[0][j] = j; + } + + // Fill in the rest of the matrix + for (let i = 1; i <= targetString.length; i++) { + for (let j = 1; j <= sourceString.length; j++) { + let cost = 1; + if (targetString.charAt(i-1) === sourceString.charAt(j-1)) { + cost = 0; + } + matrix[i][j] = Math.min(matrix[i-1][j-1] + cost, // substitution + matrix[i][j-1] + 1, // insertion + matrix[i-1][j] + 1 // deletion + ); + } + } + return matrix[targetString.length][sourceString.length]; +} + +//console.log(getEditDistance("saturday", "sunday")); //sollte 3 ergeben