I'm trying to solve a problem: Given a string made of digits [0-9], return a string where each digit is repeated a number of times equals to its value. I did the repetition of numbers, how next - I don’t know.
function explode(s) {
for (let i=0; i < s.length; i++){
let y = s[i].repeat(s[i]);
console.log(y);
}
}
Javascript is good at coercing numbers to string and vice versa but I prefer to make clear when a numerical character is being treated as a number and when it is intended to be a string.
My snippet tests processing of numbers, string representations of numbers, strings having mixtures of number and letter characters, and letter strings.
it makes use of array.split()
to for the character array, array.map()
to process the characters (including parseInt
to formally change the character to a number when used as the argument the string.repeat()
, and array.join()
to return the desired numeric string after processing:
let number = 6789;
let numberString = "12345";
let badNum = "3bad2Number";
let noNum = "justLetters";
console.log(expandNums(number));
console.log(expandNums(numberString));
console.log(expandNums(badNum));
console.log(expandNums(noNum));
function expandNums(numOrString) {
let numString = numOrString.toString();
let chars = numString.split('');
let processed = chars.map(char => char.repeat(parseInt(char)));
return processed.join('');
} // end function expandNums
The function performs well under all use situations tested, so is unlikely to throw an error if a bad argument is passes. It also does a good job with the mixed letter/number example.
You were only missing a result string to collect the parts
function explode(input) {
let result = '';
let s = input.toString(); // So that input can also be a number
for (let i=0; i < s.length; i++){
let y = s[i].repeat(s[i]);
result += y;
}
return result;
}