Re-creating the Lodash Library - implement .pad() exercise - help using variable in string.repeat()

Hi all,

I am trying to complete the “Implement .pad()” exercise (questions 15-18) in the recreating the Lodash library exercise Re-creating the Lodash Library

My code is as follows:

pad: (string, length) => {
    let necessaryPad = 0
    let necessaryPadFront = 0
    let necessaryPadEnd = 0
    let pad = " "
    let newString = ""
    if (string.length > length) {
      return string
    necessaryPad = string.length - length;
    necessaryPadFront = Math.floor(necessaryPad/2);
    necessaryPadEnd = necessaryPad - necessaryPadFront;
    newString = pad.repeat(necessaryPadFront) + string + pad.repeat(necessaryPadEnd);
    return newString;

When I run the code, I receive the following error:
“RangeError: Invalid count value
at String.repeat”

If I hardcode integers into the penultimate line (i.e.: pad.repeat(4) + string + pad.repeat(5)), I have no problem. Is there a way to use the string.repeat() method by passing in a variable?

Thanks so much for your help!