Skip to content

Commit ad16dd5

Browse files
committed
added answer for ch1_q6
1 parent db516ad commit ad16dd5

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
module.exports = Strings_1_6 = (function() {
2+
return {
3+
// Generates a compressed string with a trailing letter count
4+
// Solution #6 from the book.
5+
// @param {String} str - The string to compress
6+
// @retuns {Boolean} - a compressed string with a trailing letter count, if the string does not become smaller the orginal string is returned
7+
stringCompression: function(str) {
8+
var index = 0,
9+
count = 1;
10+
11+
var seed = str.charAt(0);
12+
var newStr = '';
13+
14+
while (index - 1 < str.length) {
15+
if (seed === str.charAt(index + 1)) {
16+
count++;
17+
} else {
18+
newStr += (seed + count);
19+
count = 1;
20+
seed = str.charAt(index + 1);
21+
}
22+
index++;
23+
}
24+
return newStr.length < str.length ? newStr : str;
25+
}
26+
};
27+
}());
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
require('../../test_helper');
2+
describe('1.6 #stringCompression', function() {
3+
it('returns a compressed string', function() {
4+
expect(Strings_1_6.stringCompression('aabcccccaaa')).to.be.equal('a2b1c5a3');
5+
expect(Strings_1_6.stringCompression('abcdef')).to.be.equal('abcdef');
6+
});
7+
});

0 commit comments

Comments
 (0)