0

someone can help me to understand this script:

String.prototype.padLeft = function(width, char) {

    var result = this;
    char = char || " ";

    if (this.length < width)  {
        result = new Array(width - this.length + 1).join(char) + this;
    }
    return result;
};
console.log("abc".padLeft(10,"-"));

So.. im extend the object String with a new method. The char parameter is optional (if omitted, the function will use white space) I dont have clear this part:

result = new Array(width - this.length + 1).join(char) + this;

Am i creating a new array with 8 element that are undefined and then separate them with the separetor? Is it correct? Why there is a"+1" in the array definition? Thank you in advance

3
  • array is used mostly for the join function. It is concatenated immediately. Commented Mar 14, 2017 at 19:16
  • interested code, generate a char at begin of string Commented Mar 14, 2017 at 19:18
  • the +1 is needed because joining an array of length = n, results in n-1 separators. Ex: ['a','b','c'].join('-') results in "a-b-c". But this algorithm wants n separators, so the +1. Commented Mar 14, 2017 at 19:25

2 Answers 2

1

new Array(width - this.length + 1).join(char)

This ^ is effectively saying "make an empty array with n number of slots, then join the empty slots together using the char to separate each empty slot. So, if char = "0", and n = 3, we get 000.

width - this.length + 1 is used to determine the number of characters needed to be added to beginning of the string.

Then we add that to the beginning of the original string: this

+1

You need the + 1 because of how join works.

new Array(1).join('0') = ""      // wrong
new Array(1+1).join('0') = "0"   // correct
new Array(2).join('0') = "0"     // wrong
new Array(2+1).join('0') = "00"  // correct
Sign up to request clarification or add additional context in comments.

1 Comment

The +1 is incorrect though, right? In his example it would be 10 - 3 + 1 = 8 which would make the whole string 3 + 8 = 11.
1

When you join an array with N elements, there will be N-1 separators between the elements. The code is using join to create a string with just N separators, so you need to give it an array with N+1 elements to account for this.

Comments

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.