Skip to content

Commit 9d74847

Browse files
committed
Refactor 1.6 solution to account for more test cases
1 parent 29b0c1d commit 9d74847

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

JavaScript/chapter01/1.6 - String Compression/rroque98_sol.js

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
/* 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.
35
Ex: 'aabcccccaaa' would become a2b1c5a3
46
*/
57

@@ -8,9 +10,9 @@ const stringCompression = (str) => {
810
return '';
911
}
1012
var compStr = '';
11-
var count = 1;
13+
var count = 0;
1214
var currentChar = str[0];
13-
for (let i = 1; i < str.length; i++) {
15+
for (let i = 0; i < str.length; i++) {
1416
let char = str[i];
1517
if (char === currentChar) {
1618
count++;
@@ -23,11 +25,16 @@ const stringCompression = (str) => {
2325
count = 1;
2426
}
2527
}
28+
if (compStr.length > str.length) {
29+
return str;
30+
}
2631
return compStr;
2732
}
2833

2934
// TESTS
3035
console.log(stringCompression('aabcccccaaa') === 'a2b1c5a3');
3136
console.log(stringCompression('cccccccc') === 'c8');
3237
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');

0 commit comments

Comments
 (0)