Wednesday, 20 October 2021

Codewars Coding Challenge: Mumbling



Mumbling


Challenge:

This time no story, no theory. The examples below show you how to write the function accum()

Examples:

accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"


Solution:

step 1: Create a function accum with the argument str

const accum = function (str) {
}
accum();

step 2: Create a new empty string variable to store the string variable in the for loop. For loop is used to iterate each string and generate n times the same string if it is the nth place (i.e) if the string variable is "abc", "a" should repeat once, "b" should repeat twice and "c" should repeat thrice.To get this repeat() method is used.

const accum = function (str) {

let newStr = '';
for (let i = 0; i < str.length; i++) {
newStr = str[i].repeat(i + 1);
console.log(newStr);
}
}
accum('abc');

// Result
// a
// bb
// ccc

step 3: Create a new empty array variable, so the new string which has been generated can be stored in the array. So that we can use methods to change the first letter to upper case and other letter to lower case.To get this charAt(), toUpperCase(), toLowerCase(), slice(), join() methods are used



const accum = function (str) {

let newStr = '';
let arr = [];

for (let i = 0; i < str.length; i++) {
newStr = str[i].repeat(i + 1);
arr[i] = newStr;
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1).toLowerCase();
}
const newArr = arr.join('-');
console.log(newArr);

return newArr;
}
accum('CaNDy');

// Result
// C-Aa-Nnn-Dddd-Yyyyy



The above challenge is to test understanding in looping, array, methods and the string.

Happy coding!!!

Have a good day!!!  

No comments:

Post a Comment

Array Destructuring

  Destructuring  Destructuring is an ES6/ES2015 feature. Destructuring allows us to break down the complex data structure into a simple data...