File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
JavaScript/chapter01/1.5 - OneAway Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* There are 3 types of edits that can be made on a string:
2
+ insert character, remove character, replace a character
3
+ Given 2 strings write a function that will check if it is
4
+ 1 or 0 edits away*/
5
+
6
+ const isOneAway = ( str1 , str2 ) => {
7
+ if ( str1 . length === str2 . length ) {
8
+ let errorCount = 0 ;
9
+ for ( let i = 0 ; i < str1 . length ; i ++ ) {
10
+ if ( str1 [ i ] !== str2 [ i ] ) {
11
+ errorCount ++ ;
12
+ }
13
+ if ( errorCount > 1 ) {
14
+ return false ;
15
+ }
16
+ }
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 ++ ;
30
+ }
31
+ // ***** Helper functions ********
32
+ function findLongestStr ( str1 , str2 ) {
33
+ str1 > str2 ? str1 : str2 ;
34
+ }
35
+ }
36
+ return true ;
37
+ }
38
+
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 ) ;
You can’t perform that action at this time.
0 commit comments