Lodash - .pad()


I’m recreating the lodash library in this project: Lodash library.
I’m dealing with the .pad() method, wondering which is the most efficient way to solve it.

Here are my solutions:

-Using a while loop:

    pad(string, length) {
        while(string.length < length) {
            string = string + ' ';
            if(string.length < length) string = ' ' + string;
        return string;

-using .repeat()

    pad(string, length) {
      let adjustment = 0;
      let padding = length - string.length;
      if(padding%2 === 1) {
          padding --;
          adjustment ++;
      string = ' '.repeat(padding/2) + string + ' '.repeat(padding/2) + ' '.repeat(adjustment);
        return string;

I prefer the solution with the while loop, since the code is more concise, but i’m wondering if .repeat() could be faster to execute.

Thank you in advance!

1 Like


If I had a choice then, I (being a learner) will choose the one with while() loop due to better readability.

Also, to further decrease the execution time of the while() loop, I would preferably store the length of the string in a variable.

let strLength = string.length;
for(let i = 0; i < strLength; i++){/*DESIRED OPERATION*/}

Now, length of the string has been calculated just once whereas, in the example you have attached, the string length is being evaluated with each iteration.

Also, I am pretty sure that there are many more optimization tricks (E.g. : Reverse iteration)and I think, it would be a good exercise if we both look it up on our own.


1 Like

Hi snikhill

Thanks for your tip about string.length! I’ll write loops in that way in future!

So you would choose the while loop only for readabilty? Do you know how .repeat() works? It iterates the string addition or it is a single operation?


1 Like

Interesting solution - this noob is impressed.

I’m curious, did you test it, and if so, did it pass?

1 Like

Just an observation, but the while loop needs to check the new length of the string with each iteration, otherwise, you’d have an infinite loop.

The solution using repeat is far less work for the computer than adding a single unit of padding to the end, and possibly the beginning of the string repeatedly.

1 Like

I went with the while loop too:

    pad(text, length) {
        if (text.length >= length) return text;
        while (text.length < length) {
            text = `${text} `
            if (text.length < length) text = ` ${text}`;
        return text;

Personally it looks easier to read/understand.

In terms of speed, it doesn’t seem to make any or very little difference.

So I padded with a length of 10,000 and execution time was 0.066 seconds. Assigning the length to a variable then using that in the while loop, execution time was 0.065 seconds.

A length of 50,000 was 0.071 seconds with the length variable and 0.072 seconds without, however the .repeat() solution was 0.064 seconds so a bit faster.