Lodash .pad() code check

Hi everyone,

first time posting so I guess this is my introduction post.

I’m currently completing the Front End Engineer career path and made it to the Lodash project.

I wrote some code for the .pad() section of the project and was hoping for some suggestions to make it more elegant or simpler? The code passes the test no issue, I was just looking for a cleaner way to code it (if there is one). Any suggestions on the variable names to make it easier to understand or perhaps I used some names that might be easily confused with something. I’m still very new to this.

Thanks!

pad(str, length) {
    if (str.length > length) {
      return str;
    } else if (str.length < length) {
      let blankSpace = ' ';
      let startPad = blankSpace.repeat(Math.floor((length - str.length)/2));
      let endPad = blankSpace.repeat(Math.ceil((length - str.length)/2));
      return startPad + str + endPad;
    }
  }
};

Hi @sachadesjardins55743
Welcome to the forums!

What does the exercise say about the value to return when the length passed to the method is the same as the length of the string passed in? Right now, your method returns ‘undefined’ in this case.

There probably still is a more concise way of doing it, but this way you’d have a little less code already:

function pad2(str, length) {
	let spaces = length - str.length > 0 ? length - str.length : 0; // if length is smaller than or equal to str.length set the amount of spaces to add to zero
    let startPos = Math.floor(spaces/2);
    let arr = Array(spaces).fill(' '); // create an array with spaces to add left and right
    arr.splice(startPos, 0, str); // adds string to array 
    return arr.join(''); // return array as string
}

Ah right, sorry.

The instructions are:

  • .pad() takes two arguments: a string and a length
  • .pad() adds spaces evenly to both sides of the string to make it reach the desired length
  • Extra padding is added to the end of the string if an odd amount of padding is required to reach the specified length
  • Your method does not need to accept the additional chars parameter; we will only add space characters to pad our string

Just checked, it also says

  1. Within the method, add an if statement that checks if length is shorter than or equal to string ‘s length. If so, return string .

Your method does not return the string if the length is equal to the string’s length. Therefore I’m surprised that it passed the test. You can easily rectify that by adding the equal sign to the first condition. You could also swap the blocks and just write

if(str.length < length){
...
} else {
  return str
}
1 Like

I was under the impression that I should figure out a method that works on my own and use the walkthrough if I get stuck.

Thanks for the help!

1 Like