Sean Cook Sean Cook - 4 months ago 10
Javascript Question

Alternate adding a character to the beginning and end of string

I am trying to solve a Javascript puzzle. I need to write a function that uses a while loop to add a character to the beginning of string and then on the next loop adds the character to the end of the string and to the beginning on the loop after that. The function takes two parameters a string and a number of characters to add.
So far I have

function padIt(str,n){
//coding here
var newStr = "";
var padding = "*";
var i = 0;

while(i<=n){
if (i%2===0){
newStr = newStr+padding;
} else{
newStr = padding+str;
}
i++;
}
return newStr;
}


I am passing the first two test cases but it won't work properly for the third time through the loop. Expecting "* * a *" for n = 3 but only getting "*a". It has to be a while loop so I don't know if I am not setting the loop up correctly or if I am messing up the variables. Any help is greatly appreciated as I am totally lost.

Answer

You can do it by writing code like below,

function padIt(str,n, pad = "*"){
  var left = Math.ceil(n/2), right = n - left;
  return pad.repeat(left) + str + pad.repeat(right);
}

And this function would print,

console.log("a", 1); // "*a"
console.log("a", 2); // "*a*"
console.log("a", 10); // "*****a*****"

Thing need to be read after implementing this code,