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
2 Answers 2
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
1 Comment
+1 is incorrect though, right? In his example it would be 10 - 3 + 1 = 8 which would make the whole string 3 + 8 = 11.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.
+1is 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.