Loadash Project is not working with padStart() and padEnd()

So in this exercise, I am using the below-mentioned function. I
know this is not the right/complex way to achieve the solution using pedStart and pedEnd, but I like to complete this problem.

  pad(string1,desiredLength) {
    const currentLength = string1.length;
    if (currentLength >= desiredLength) {
      return string1 
    }
    const padLength = desiredLength - currentLength;
    const startPaddingLength = Math.floor(padLength/2);
    const endPaddingLength = desiredLength - startPaddingLength-currentLength;
    const frontPeddingLength = currentLength + startPaddingLength;
    const lastPeddingLength = currentLength + endPaddingLength;
    const fronPaddedPart = string1.padStart(frontPeddingLength,' ');
    let lastPaddedPart = string1.padEnd(lastPeddingLength,' ');
		lastPaddedPart = lastPaddedPart.substring(currentLength,lastPaddedPart.length);
    const paddedString =  fronPaddedPart + lastPaddedPart;
    return paddedString;
  },

this code is working as expected in other environments(local/online compilers) but erring out on Codecademy integrated environment with TypeError: string1.padStart is not a function

Hi Pathik,
from what I remember from that exercise, you should create an object '_' and all methods like the current pad as well as padStart are methods of that object. Which means that is you’re using one of those methods in another, you need to refer to that method with the this keyword. Otherwise they can’t be found. Maybe in the environment where you tested the methods, you tested them individually and not as part of the _ object?

Hi Mirja,
I have declared pad() method in the object and you are right about use of this but pad.Start() is a string instance method. below is working example using string instance method in the object

let a = {
		pad(string1,desiredLength) {
    const currentLength = string1.length;
    if (currentLength >= desiredLength) {
      return string1 
    }
    const padLength = desiredLength - currentLength;
    const startPaddingLength = Math.floor(padLength/2);
    const endPaddingLength = desiredLength - startPaddingLength-currentLength;
    const frontPeddingLength = currentLength + startPaddingLength;
    const lastPeddingLength = currentLength + endPaddingLength;
    const fronPaddedPart = string1.padStart(frontPeddingLength,'$');
    let lastPaddedPart = string1.padEnd(lastPeddingLength,'$');
		lastPaddedPart = lastPaddedPart.substring(currentLength,lastPaddedPart.length);
    
    const paddedString =  fronPaddedPart + lastPaddedPart;
    return paddedString;
  }
 }
console.log(a.pad('pathik',21))
1 Like

Aside

JS gives us some useful tools to simplify this method.

  • String.repeat()
  • String.slice()
  • Template literals

Consider how these might help you to reduce the code bulk of your method.

1 Like