File tree Expand file tree Collapse file tree 1 file changed +11
-4
lines changed
JavaScript/chapter01/1.6 - String Compression Expand file tree Collapse file tree 1 file changed +11
-4
lines changed Original file line number Diff line number Diff line change 1
1
/* Implement a method to perform basic string
2
- compression using the counts of repeated characters
2
+ compression using the counts of repeated characters.
3
+ If the compressed string length is more than original
4
+ string length, return original string.
3
5
Ex: 'aabcccccaaa' would become a2b1c5a3
4
6
*/
5
7
@@ -8,9 +10,9 @@ const stringCompression = (str) => {
8
10
return '' ;
9
11
}
10
12
var compStr = '' ;
11
- var count = 1 ;
13
+ var count = 0 ;
12
14
var currentChar = str [ 0 ] ;
13
- for ( let i = 1 ; i < str . length ; i ++ ) {
15
+ for ( let i = 0 ; i < str . length ; i ++ ) {
14
16
let char = str [ i ] ;
15
17
if ( char === currentChar ) {
16
18
count ++ ;
@@ -23,11 +25,16 @@ const stringCompression = (str) => {
23
25
count = 1 ;
24
26
}
25
27
}
28
+ if ( compStr . length > str . length ) {
29
+ return str ;
30
+ }
26
31
return compStr ;
27
32
}
28
33
29
34
// TESTS
30
35
console . log ( stringCompression ( 'aabcccccaaa' ) === 'a2b1c5a3' ) ;
31
36
console . log ( stringCompression ( 'cccccccc' ) === 'c8' ) ;
32
37
console . log ( stringCompression ( '' ) === '' ) ;
33
- console . log ( stringCompression ( 'AabccCccaaa' ) === 'A1a1b1c2C1c2a3' ) ;
38
+ console . log ( stringCompression ( 'AabccCccaaa' ) === 'AabccCccaaa' ) ;
39
+ // Explanation: 'A1a1b1c2C1c2a3' length is longer than original string so returns original string
40
+ console . log ( stringCompression ( 'x' ) === 'x' ) ;
You can’t perform that action at this time.
0 commit comments