Skip to content

tests: Levenshtein Distance (dynamic programming solution) #1114

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ npm test
If you want save some time and just run a specific test:

```shell
# this will run any test file where the filename matches "koch"
# This will run any test file where the filename contains "koch" (no need to specify folder path)
npm test -- koch
```

Expand Down
12 changes: 8 additions & 4 deletions Dynamic-Programming/LevenshteinDistance.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
/**
* A Dynamic Programming based solution for calculation of the Levenshtein Distance
* https://en.wikipedia.org/wiki/Levenshtein_distance
* @function calculateLevenshteinDp
* @description A Dynamic Programming based solution for calculation of the Levenshtein Distance.
* @param {String} x - Word to be converted.
* @param {String} y - Desired result after operations.
* @return {Integer} The Levenshtein distance between x and y.
* @see [Levenshtein_distance](https://en.wikipedia.org/wiki/Levenshtein_distance)
*/

function minimum (a, b, c) {
Expand All @@ -18,7 +22,7 @@ function costOfSubstitution (x, y) {
}

// Levenshtein distance between x and y
function calculate (x, y) {
function calculateLevenshteinDp (x, y) {
const dp = new Array(x.length + 1)
for (let i = 0; i < x.length + 1; i++) {
dp[i] = new Array(y.length + 1)
Expand All @@ -39,4 +43,4 @@ function calculate (x, y) {
return dp[x.length][y.length]
}

export { calculate }
export { calculateLevenshteinDp }
19 changes: 19 additions & 0 deletions Dynamic-Programming/tests/LevenshteinDistance.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { calculateLevenshteinDp } from '../LevenshteinDistance'

test('Should return the distance counting additions and removals', () => {
const from = 'kitten'
const to = 'sitting'
expect(calculateLevenshteinDp(from, to)).toBe(3)
})

test('Should return the distance based on replacements in the middle of the strings', () => {
const from = 'book'
const to = 'back'
expect(calculateLevenshteinDp(from, to)).toBe(2)
})

test('Should return the distance for strings with different length', () => {
const from = 'sunday'
const to = 'saturday'
expect(calculateLevenshteinDp(from, to)).toBe(3)
})