Sean Cook
Sean Cook

Reputation: 13

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.

Upvotes: 1

Views: 467

Answers (3)

Shamanchyk
Shamanchyk

Reputation: 1

function padIt(str,n){
  while(n>0){
    if(n%2 === 0){
      str = str + '*';
    } else{
      str = '*' + str;
    }
    n--;
  }
  return str;
}

Upvotes: 0

David R
David R

Reputation: 15639

You need to comment your newStr+=padding; line.

Here is the refined code,

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

  while(i<=n){
    i++;
    newStr=padding+str;
    //newStr+=padding;
}

  return newStr;

}

HTH

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

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,

Upvotes: 1

Related Questions