index.js
 1  'use strict';
 2  const array = [];
 3  const charCodeCache = [];
 4  
 5  const leven = (left, right) => {
 6  	if (left === right) {
 7  		return 0;
 8  	}
 9  
10  	const swap = left;
11  
12  	// Swapping the strings if `a` is longer than `b` so we know which one is the
13  	// shortest & which one is the longest
14  	if (left.length > right.length) {
15  		left = right;
16  		right = swap;
17  	}
18  
19  	let leftLength = left.length;
20  	let rightLength = right.length;
21  
22  	// Performing suffix trimming:
23  	// We can linearly drop suffix common to both strings since they
24  	// don't increase distance at all
25  	// Note: `~-` is the bitwise way to perform a `- 1` operation
26  	while (leftLength > 0 && (left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength))) {
27  		leftLength--;
28  		rightLength--;
29  	}
30  
31  	// Performing prefix trimming
32  	// We can linearly drop prefix common to both strings since they
33  	// don't increase distance at all
34  	let start = 0;
35  
36  	while (start < leftLength && (left.charCodeAt(start) === right.charCodeAt(start))) {
37  		start++;
38  	}
39  
40  	leftLength -= start;
41  	rightLength -= start;
42  
43  	if (leftLength === 0) {
44  		return rightLength;
45  	}
46  
47  	let bCharCode;
48  	let result;
49  	let temp;
50  	let temp2;
51  	let i = 0;
52  	let j = 0;
53  
54  	while (i < leftLength) {
55  		charCodeCache[i] = left.charCodeAt(start + i);
56  		array[i] = ++i;
57  	}
58  
59  	while (j < rightLength) {
60  		bCharCode = right.charCodeAt(start + j);
61  		temp = j++;
62  		result = j;
63  
64  		for (i = 0; i < leftLength; i++) {
65  			temp2 = bCharCode === charCodeCache[i] ? temp : temp + 1;
66  			temp = array[i];
67  			// eslint-disable-next-line no-multi-assign
68  			result = array[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2;
69  		}
70  	}
71  
72  	return result;
73  };
74  
75  module.exports = leven;
76  // TODO: Remove this for the next major release
77  module.exports.default = leven;