Skip to content

Commit 6d54def

Browse files
committed
Refactor 1.6 solution to address for-if antipattern and unnecessary var keywords
1 parent 9d74847 commit 6d54def

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed
Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/* Implement a method to perform basic string
1+
/* Implement a method to perform basic string
22
compression using the counts of repeated characters.
33
If the compressed string length is more than original
44
string length, return original string.
@@ -9,22 +9,20 @@ const stringCompression = (str) => {
99
if (!str.length) {
1010
return '';
1111
}
12-
var compStr = '';
13-
var count = 0;
14-
var currentChar = str[0];
12+
let compStr = '';
13+
let count = 0;
14+
let currentChar = str[0];
1515
for (let i = 0; i < str.length; i++) {
1616
let char = str[i];
1717
if (char === currentChar) {
1818
count++;
19-
if (i === str.length - 1) {
20-
compStr += `${currentChar}${count}`;
21-
}
2219
} else {
2320
compStr += `${currentChar}${count}`;
2421
currentChar = char;
2522
count = 1;
2623
}
2724
}
25+
compStr += `${currentChar}${count}`;
2826
if (compStr.length > str.length) {
2927
return str;
3028
}
@@ -35,6 +33,6 @@ const stringCompression = (str) => {
3533
console.log(stringCompression('aabcccccaaa') === 'a2b1c5a3');
3634
console.log(stringCompression('cccccccc') === 'c8');
3735
console.log(stringCompression('') === '');
38-
console.log(stringCompression('AabccCccaaa') === 'AabccCccaaa');
36+
console.log(stringCompression('AabccCccaaa') === 'AabccCccaaa');
3937
// Explanation: 'A1a1b1c2C1c2a3' length is longer than original string so returns original string
4038
console.log(stringCompression('x') === 'x');

0 commit comments

Comments
 (0)