-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.edit.one.js
More file actions
51 lines (43 loc) · 1.12 KB
/
string.edit.one.js
File metadata and controls
51 lines (43 loc) · 1.12 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
/*
* @title: String Edits
* @description: validate one edit between two strings
* @author: Thorsten Kober
* @email: [email protected]
*/
function oneEditAway(str1, str2) {
const length1 = str1.length;
const length2 = str2.length;
if (Math.abs(length1 - length2) > 1) return false;
let index1 = 0;
let index2 = 0;
let numEdits = 0;
while (index1 < length1 && index2 < length2) {
if (str1[index1] !== str2[index2]) {
if (numEdits >= 1) return false;
if (length1 > length2) {
index1++;
} else if (length2 > length1) {
index2++;
} else {
index1++;
index2++;
}
numEdits++;
} else {
index1++;
index2++;
}
}
if (index1 < length1 || index2 < length2) {
numEdits++;
}
return numEdits === 1;
}
// npx jest algorithms/string/string.edit.one.js
test('oneEditAway()', () => {
expect(oneEditAway('car', 'cart')).toBe(true);
expect(oneEditAway('car', 'cto')).toBe(false);
expect(oneEditAway('car', 'com')).toBe(false);
expect(oneEditAway('car', 'mar')).toBe(true);
expect(oneEditAway('pale', 'ple')).toBe(true);
});