Skip to content

Commit 3f60757

Browse files
committed
Refactor 1.5 OneAway logic and add more tests
1 parent f533992 commit 3f60757

File tree

1 file changed

+32
-7
lines changed

1 file changed

+32
-7
lines changed

JavaScript/chapter01/1.5 - OneAway/rroque98_sol.js

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@ const isOneAway = (str1, str2) => {
77
if (str1.length === str2.length) {
88
let errorCount = 0;
99
for (let i = 0; i < str1.length; i++) {
10-
if (str1[i] !== str2[i]) {
11-
errorCount++;
10+
if (str1[i] === str2[i]) {
11+
continue;
1212
}
13+
errorCount++;
1314
if (errorCount > 1) {
1415
return false;
1516
}
@@ -18,19 +19,32 @@ const isOneAway = (str1, str2) => {
1819
let errorCount = 0;
1920
const longestStr = findLongestStr(str1, str2);
2021
let x = 0;
21-
for(let i = 0; i < longestStr; i++) {
22-
if (str1[i] !== str2[x]) {
23-
errorCount++;
22+
for(let i = 0; i < longestStr.length; i++) {
23+
let currentChar1 = str1[i];
24+
let currentChar2 = str2[x]
25+
let nextChar1 = str1[i + 1];
26+
let nextChar2 = str2[x + 1];
27+
if (str1[i] === str2[x]) {
2428
x++;
29+
continue;
2530
}
31+
errorCount++;
2632
if (errorCount > 1) {
2733
return false;
2834
}
29-
x++;
35+
if (currentChar1 === nextChar2) {
36+
x++;
37+
i--;
38+
continue;
39+
} else if (currentChar2 === nextChar1) {
40+
continue;
41+
}
42+
errorCount++;
43+
return false;
3044
}
3145
// ***** Helper functions ********
3246
function findLongestStr(str1, str2) {
33-
str1 > str2 ? str1 : str2;
47+
return (str1.length > str2.length ? str1 : str2);
3448
}
3549
}
3650
return true;
@@ -41,3 +55,14 @@ console.log(isOneAway('pale', 'ple') === true);
4155
console.log(isOneAway('pales', 'pale') === true);
4256
console.log(isOneAway('pale', 'bale') === true);
4357
console.log(isOneAway('pale', 'bake') === false);
58+
console.log(isOneAway('paleo', 'palseo') === true);
59+
console.log(isOneAway('p', 'b') === true);
60+
console.log(isOneAway('', '') === true);
61+
console.log(isOneAway('p', 'p') === true);
62+
console.log(isOneAway('pale', 'ppalpe') === false);
63+
64+
console.log(isOneAway('ple', 'pale') === true);
65+
console.log(isOneAway('pale', 'pales') === true);
66+
console.log(isOneAway('bale', 'pale') === true);
67+
console.log(isOneAway('bake', 'pale') === false);
68+
console.log(isOneAway('palseo', 'paleo') === true);

0 commit comments

Comments
 (0)