@@ -4,40 +4,69 @@ Given 2 strings write a function that will check if it is
4
4
1 or 0 edits away*/
5
5
6
6
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 ;
7
13
if ( str1 . length === str2 . length ) {
8
- let errorCount = 0 ;
9
14
for ( let i = 0 ; i < str1 . length ; i ++ ) {
10
15
if ( str1 [ i ] !== str2 [ i ] ) {
11
16
errorCount ++ ;
12
- }
13
- if ( errorCount > 1 ) {
14
- return false ;
17
+ if ( errorCount > 1 ) {
18
+ return false ;
19
+ }
15
20
}
16
21
}
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 ;
30
29
}
31
- // ***** Helper functions ********
32
- function findLongestStr ( str1 , str2 ) {
33
- str1 > str2 ? str1 : str2 ;
30
+ errorCount ++ ;
31
+ if ( errorCount > 1 ) {
32
+ return false ;
34
33
}
35
34
}
36
35
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
+ }
37
45
}
38
46
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