"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Repeat the Character in a string based on its Alphabetical index

Repeat the Character in a string based on its Alphabetical index

Published on 2024-11-03
Browse:614

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
Release Statement This article is reproduced at: https://dev.to/dindustack/repeat-the-character-in-a-string-based-on-its-alphabetical-index-1ln7?1 If there is any infringement, please contact [email protected] delete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3