I'm trying to solve this exercise which goal is to give me a string that has to be turned into another string. The characters of the new string are repeated like in the example below.
Example:
accum("abcd"); // "A-Bb-Ccc-Dddd"
I wrote the following code:
function accum(s) {
counter = 0;
for (var i = 0; i < s.length; i++) {
return s[i].toUpperCase() + s[i].repeat(counter) + "-";
counter += 1;
}
}
When I try to run a sample test such as ZpglnRxqenU I get this error:
Expected: 'Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu', instead got: 'Z-'.
Apparently the problem is linked to the loop which is not working, but I can't figure out why.
Here's an ES6 one-liner :
const accum = word => word.toLowerCase().split("").map( (letter,index) => letter.toUpperCase() + letter.repeat(index) ).join("-")
console.log( accum("ZpglnRxqenU") )
Explanation :
word.split("") Start with breaking your string into an array of letters.map( (letter,index) => Iterate each letter, keeping track of the index as you goletter.toUpperCase() + letter.repeat(index) Replace each letter with the transformed value that you return.join("-") Join everything back to a string with "-" as a separator. You can combine the use of the methods: String.prototype.split(), Array.prototype.map() and Array.prototype.join():
function accum(s) {
return s
.split('')
.map(function (e, i) {
return e.toUpperCase() + e.repeat(i);
})
.join('-');
}
console.log(accum('ZpglnRxqenU'));
ES6:
const accum = s => s.split('').map((e, i) => e.toUpperCase() + e.repeat(i)).join('-');
console.log(accum('ZpglnRxqenU'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With