File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed
lib/data-structures/chapter-1
test/data-structures/chapter-1 Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ module . exports = Strings_1_5 = ( function ( ) {
2+ return {
3+ // Checks if a string can converted to another string with a single edit
4+ // Solution #5 from the book.
5+ // @param {String } first - first string
6+ // @param {String } second - second string
7+ // @retuns {Boolean} - true if a string can converted to another string with a single edit
8+ oneAway : function ( first , second ) {
9+
10+ var skip = true ;
11+ var s1 = first . length > second . length ? first : second ;
12+ var s2 = first . length > second . length ? second : first ;
13+ var diff = s1 . length - s2 . length ;
14+ var i1 = 0 ,
15+ i2 = 0 ;
16+
17+ if ( diff > 1 ) {
18+ return false ;
19+ }
20+ while ( i1 < s2 . length ) {
21+ var i2 = i1 + ( ! skip ? diff : 0 ) ;
22+ if ( s1 . charCodeAt ( i2 ) !== s2 . charCodeAt ( i1 ) ) {
23+ if ( skip ) {
24+ i1 = i1 - diff ;
25+ skip = false ;
26+ } else {
27+ return false ;
28+ }
29+ }
30+ i1 ++ ;
31+ }
32+ return true ;
33+ }
34+ } ;
35+ } ( ) ) ;
Original file line number Diff line number Diff line change 1+ require ( '../../test_helper' ) ;
2+ describe ( '1.5 #oneAway' , function ( ) {
3+ it ( 'returns true if a string can converted to another string with a single edit' , function ( ) {
4+ expect ( Strings_1_5 . oneAway ( 'pale' , 'ple' ) ) . to . be . true ;
5+ expect ( Strings_1_5 . oneAway ( 'pales' , 'pale' ) ) . to . be . true ;
6+ expect ( Strings_1_5 . oneAway ( 'pale' , 'bale' ) ) . to . be . true ;
7+ } ) ;
8+ it ( 'returns false if a string can not be converted to another string in a single edit' , function ( ) {
9+ expect ( Strings_1_5 . oneAway ( 'pale' , 'ble' ) ) . to . be . false ;
10+ } ) ;
11+ } ) ;
You can’t perform that action at this time.
0 commit comments