Search code examples
javascripttostringtrimtest-pyramid

How do I go about trimming spaces within my triangle


For some reason, I just can't make .trim work for me. I thought maybe it's better to try turning my code into a string then trim but can't properly use toString either it seems. Here's what I've got so far:

function Pyramid(number) {
  if(number>0) {
    Pyramid(number-1);
    for(let z=9;  z>=(number-1);  z--) {
      document.write("  ");
    };
    for(let j=1; j<=number; j++) { //12345
      document.write(" "+j);
    };
    for(let k=number-1; k>0; k--) { // 54321
      document.write(" "+k);
    };
  }; 
  document.write("<br>");
};

Pyramid(5);
document.body.style.fontFamily = "monospace";

function myFunction() {
  var n = Pyramid(5).toString();
  document.write(n);
};

myFunction();

document.write(myFunction.trim()); 

If anyone could make this mess work it would also be nice to have it's longest line touch the left side of the screen, probably need to trim spaces from the left but afraid I'd ruin the pyramid shape.


Solution

  • Looks like your first loop wherein you print the initial set of spaces is the root cause for your issue. The size of the pyramid can be variable and hardcoding the number 9 will result into unwanted spaces when the size is less than 9.

    A simple work-around is to remember the size of pyramid when printing spaces. You can achieve this by having a simple wrapper function which feeds the initial size as the second param to your recursive function.

    function Pyramid(number) {
      buildPyramid(number, number);
    }
    
    function buildPyramid(currentVal, size) {
      if (currentVal > 0) {
        buildPyramid(currentVal - 1, size);
        for (let z = size; z > currentVal; z--) {
          document.write(" &nbsp;");
        }
        for (let j = 1; j <= currentVal; j++) {
          document.write(" " + j);
        }
        for (let k = currentVal - 1; k > 0; k--) {
          document.write(" " + k);
        }
      }
      document.write("<br>");
    }
    Pyramid(5);
    document.body.style.fontFamily = "monospace";