1

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.

1
  • You need to comment/remove your //newStr+=padding; line. Commented Jul 27, 2016 at 17:36

3 Answers 3

1

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,

Sign up to request clarification or add additional context in comments.

1 Comment

Not a while loop but I think this is definitely how I should use the variables.
0

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

Comments

0

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

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.