Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping through a string and using repeat method

Tags:

javascript

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.

like image 699
InnSaei Avatar asked Feb 09 '26 19:02

InnSaei


2 Answers

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 go
  • letter.toUpperCase() + letter.repeat(index) Replace each letter with the transformed value that you return
  • At this point, you have an array of transformed values
  • .join("-") Join everything back to a string with "-" as a separator.
like image 75
Jeremy Thille Avatar answered Feb 12 '26 08:02

Jeremy Thille


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'));
like image 33
Yosvel Quintero Arguelles Avatar answered Feb 12 '26 07:02

Yosvel Quintero Arguelles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!