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
+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.