curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69162d64f96574d9bb629f04.md
Given a string sentence, return a compressed version of the sentence where consecutive duplicate words are replaced by the word followed with the number of times it repeats in parentheses.
For example, given "yes yes yes please", return "yes(3) please".
compressString("yes yes yes please") should return "yes(3) please".
assert.equal(compressString("yes yes yes please"), "yes(3) please");
compressString("I have have have apples") should return "I have(3) apples".
assert.equal(compressString("I have have have apples"), "I have(3) apples");
compressString("one one three and to the the the the") should return "one(2) three and to the(4)".
assert.equal(compressString("one one three and to the the the the"), "one(2) three and to the(4)");
compressString("route route route route route route tee tee tee tee tee tee") should return "route(6) tee(6)".
assert.equal(compressString("route route route route route route tee tee tee tee tee tee"), "route(6) tee(6)");
function compressString(sentence) {
return sentence;
}
function compressString(sentence) {
const words = sentence.split(" ");
const result = [];
let count = 1;
for (let i = 0; i < words.length; i++) {
if (words[i] === words[i + 1]) {
count++;
} else {
if (count > 1) {
result.push(`${words[i]}(${count})`);
} else {
result.push(words[i]);
}
count = 1;
}
}
return result.join(" ");
}