forked from mgechev/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlevenshtein-distance.js
More file actions
51 lines (46 loc) · 1.46 KB
/
levenshtein-distance.js
File metadata and controls
51 lines (46 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
(function (exports) {
'use strict';
var levenshteinDistance = (function () {
function levenshteinDistance(s, ls, t, lt) {
if (ls === 0) {
return lt;
}
if (lt === 0) {
return ls;
}
var cost;
if (s[ls - 1] === t[lt - 1]) {
cost = 0;
} else {
cost = 1;
}
return Math.min(levenshteinDistance(s, ls - 1, t, lt) + 1,
levenshteinDistance(s, ls, t, lt - 1) + 1,
levenshteinDistance(s, ls - 1, t, lt - 1) + cost);
}
/**
* The Levenshtein distance between two strings is a minimum number
* of edits needed to transform one string into the other, with the
* allowable edit operations being insertion, deletion,
* or substitution of a single character.
*
* @public
* @module others/levenshtein-distance
*
* @example
*
* var dist = require('path-to-algorithms/src/others/' +
* 'levenshtein-distance').levenshteinDistance;
* console.log(dist('kitten', 'sitting')); // 3
*
* @param {String} s Source string.
* @param {String} t Target string.
* @return {Number} Minimum number of edits needed
* to transform source string into the target string.
*/
return function (s, t) {
return levenshteinDistance(s, s.length, t, t.length);
};
}());
exports.levenshteinDistance = levenshteinDistance;
}(typeof exports === 'undefined' ? window : exports));