Re-creating the lodash library - .pad() need help

I am having an error with the _.pad() method. Here is my code and the error"

pad(string, length) {
if (length <= string.length) {
return string;
}

/* add padding to front and end of string */
let startPaddingLength = Math.floor((string.length - length)/2);      
let endPaddingLength = length - string.length - startPaddingLength;

var space = ' ';
var paddedString = space.repeat(startPaddingLength) + string + space.repeat(endPaddingLength);

return paddedString;

}

Error I am getting:

1 Like

I think you might get some answers when you log endPaddingLength after its declaration and before you determine paddedString ;).

console.log(endPaddingLength);

Thanks for pointing me in that direction. It turns out I had my string.length and length flipped in my Math.floor() call.

Thanks.

1 Like

Yep which resulted in a negative number. And negative numbers return a RangeError on repeat() :wink: .
Glad you figured that out :smiley: . Could you by any chance mark my reply as the solution to your problem (checkbox at that reply)?