Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i repeat a string multiple times according to its index in a string

I am trying to write a function with a string as a parameter, and the output should be the same string with each character repeated as many times as the character's index, with capitalizing the first letter.

For example, function accum(abc) should return: A-Bb-Ccc

accum(zytx) should return: Z-Yy-Ttt-Xxxx

I tried the following code but it is not working. Can someone help me out?

function accum(s) {
  var strSplit = s.toLowerCase().split('');

  var newArr = strSplit.map((element, i) => 
  element.repeat(i+1).charAt(0).toUpperCase()+element.substr(1));

  console.log("the new Arr is: "+newArr.join('-'));
  return newArr.join('-');
}

accum("abcd");
like image 556
Elias Rub Avatar asked Jan 02 '23 23:01

Elias Rub


2 Answers

In functional style (thanks to @Redu for the comment):

const accum = (s) => Array.from(
    s,
    (c, i) => `${c.toLocaleUpperCase()}${c.repeat(i)}`
  )
  .join('-');

console.log(accum(''));
console.log(accum('a'));
console.log(accum('xyz'));

Your code doesn't work because in this line

element.repeat(i+1).charAt(0).toUpperCase()+element.substr(1))

element.substr(1) tries to get the substring starting at index 1 of a single character (which is always the empty string). You probably thought that element.repeat(i+1) would work in place (i.e. modify element) whereas it returns a new string (see MDN).

You can fix this as follows:

function accum(s) {
  var strSplit = s.toLowerCase().split('');

  var newArr = strSplit.map((element, i) => 
  `${element.toLocaleUpperCase()}${element.repeat(i)}`);

  console.log("the new Arr is: "+newArr.join('-'));
  return newArr.join('-');
}

accum("abcd");
like image 129
FK82 Avatar answered Jan 04 '23 12:01

FK82


The problem is your .charAt(0) which is always taking the first character, and you're not repeating the lowercase letters afterwards.

function accum(s) {

  var strSplit = s.toLowerCase().split('');

  var newArr = strSplit.map(
    (element, i) => element.toUpperCase()+element.repeat(i));

  return newArr.join('-');
}

console.log("the new Arr is:", accum("abcd"));
console.log("zytx:", accum("zytx"));

You can simplify this even further, by removing the .substr() and just put element.repeat(i). On the first iteration, i will be 0 and return an empty string.

like image 30
ugh StackExchange Avatar answered Jan 04 '23 12:01

ugh StackExchange