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!


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?


Interesting solution - this noob is impressed.

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

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.