Skip to content

Commit efc4b34

Browse files
authored
Merge pull request #27 from rroque98/OneAwaySolutionBranch
Refactor JavaScript 1.5 One Away solution
2 parents c6538cb + b51e25c commit efc4b34

File tree

1 file changed

+54
-25
lines changed

1 file changed

+54
-25
lines changed

JavaScript/chapter01/1.5 - OneAway/rroque98_sol.js

Lines changed: 54 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,40 +4,69 @@ Given 2 strings write a function that will check if it is
44
1 or 0 edits away*/
55

66
const isOneAway = (str1, str2) => {
7+
const diffInLen = Math.abs(str1.length - str2.length);
8+
if (diffInLen > 1) {
9+
return false;
10+
}
11+
12+
let errorCount = 0;
713
if (str1.length === str2.length) {
8-
let errorCount = 0;
914
for (let i = 0; i < str1.length; i++) {
1015
if (str1[i] !== str2[i]) {
1116
errorCount++;
12-
}
13-
if (errorCount > 1) {
14-
return false;
17+
if (errorCount > 1) {
18+
return false;
19+
}
1520
}
1621
}
17-
} else {
18-
let errorCount = 0;
19-
const longestStr = findLongestStr(str1, str2);
20-
let x = 0;
21-
for(let i = 0; i < longestStr; i++) {
22-
if (str1[i] !== str2[x]) {
23-
errorCount++;
24-
x++;
25-
}
26-
if (errorCount > 1) {
27-
return false;
28-
}
29-
x++;
22+
return true;
23+
}
24+
const longStr = str1.length > str2.length ? str1 : str2;
25+
const shortStr = str1.length <= str2.length ? str1 : str2;
26+
for (let i = 0; i + errorCount < longStr.length; i++) {
27+
if (longStr[i + errorCount] === shortStr[i]) {
28+
continue;
3029
}
31-
// ***** Helper functions ********
32-
function findLongestStr(str1, str2) {
33-
str1 > str2 ? str1 : str2;
30+
errorCount++;
31+
if (errorCount > 1) {
32+
return false;
3433
}
3534
}
3635
return true;
36+
};
37+
38+
// ****** TESTS ******
39+
function runTests(cases, expected) {
40+
for (const [str1, str2] of cases) {
41+
console.log(
42+
isOneAway(str1, str2) === expected && isOneAway(str2, str1) === expected
43+
);
44+
}
3745
}
3846

39-
// TESTS
40-
console.log(isOneAway('pale', 'ple') === true);
41-
console.log(isOneAway('pales', 'pale') === true);
42-
console.log(isOneAway('pale', 'bale') === true);
43-
console.log(isOneAway('pale', 'bake') === false);
47+
runTests(
48+
[
49+
['pale', 'ple'], // deletion
50+
['pale', 'opale'], // insertion in beginning
51+
['pale', 'palse'], // insertion in middle
52+
['pale', 'pales'], // insertion at end
53+
['pale', 'bale'], // replacement
54+
['p', 'b'],
55+
['p', 'p'],
56+
['p', ''],
57+
['', '']
58+
],
59+
true
60+
);
61+
62+
runTests(
63+
[
64+
['pale', 'ae'], // greater than 1 deletions
65+
['pale', 'ppalpe'], // greater than 1 insertions
66+
['pale', 'bake'], // greater than 1 replacements
67+
['pale', 'balpe'], // 1 insertion, 1 replacement
68+
['pale', 'plo'], // 1 deletion, 1 replacement
69+
['pale', 'ales'] // 1 deletion, 1 insertion
70+
],
71+
false
72+
);

0 commit comments

Comments
 (0)