Home  >  Article  >  Web Front-end  >  Repeat the Character in a string based on its Alphabetical index

Repeat the Character in a string based on its Alphabetical index

Susan Sarandon
Susan SarandonOriginal
2024-10-18 14:57:02434browse

Repeat the Character in a string based on its Alphabetical index

Write a function repeatAlpha that takes a string and displays it
repeating each alphabetical character as many times as its alphabetical index.

Solution

const range = (start, stop, step) =>
  Array.from(
    { length: Math.ceil((stop - start) / step) },
    (_, i) => start + i * step
  );

const upperAlpha = range("A".charCodeAt(0), "Z".charCodeAt(0) + 1, 1).map((x) =>
  String.fromCharCode(x)
);

const lowerAlpha = range("a".charCodeAt(0), "z".charCodeAt(0) + 1, 1).map((x) =>
  String.fromCharCode(x)
);

function getAlphaIndex(char) {
  if (char === char.toUpperCase()) {
    return upperAlpha.indexOf(char) + 1;
  }

  if (char === char.toLowerCase()) {
    return lowerAlpha.indexOf(char) + 1;
  }
}

function repeatAlpha(text) {
  let occurrence = [];

  Array.from(text).forEach((char) => {
    let count = getAlphaIndex(char);
    let result = Array(count).fill(char).join("");
    occurrence.push(result);
  });

  return occurrence.join("");
}

console.log(repeatAlpha("Becky"));
console.log(repeatAlpha("neNgi"));
console.log(repeatAlpha("ChInwendu"));
console.log(repeatAlpha("dindustack"));

Result

BBeeeeeccckkkkkkkkkkkyyyyyyyyyyyyyyyyyyyyyyyyy
nnnnnnnnnnnnnneeeeeNNNNNNNNNNNNNNgggggggiiiiiiiii
CCChhhhhhhhIIIIIIIIInnnnnnnnnnnnnnwwwwwwwwwwwwwwwwwwwwwwweeeeennnnnnnnnnnnnndddduuuuuuuuuuuuuuuuuuuuu
ddddiiiiiiiiinnnnnnnnnnnnnndddduuuuuuuuuuuuuuuuuuuuusssssssssssssssssssttttttttttttttttttttaccckkkkkkkkkkk

The above is the detailed content of Repeat the Character in a string based on its Alphabetical index. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn