DEV Community

Discussion on: Daily Challenge #2 - String Diamond

Collapse
 
jasman7799 profile image
Jarod Smith • Edited
// Will print a diamond with n stars in the middle line
function printDiamond(n) {

  // validate input
  if (n % 2 === 0)
    throw new Error("can't have middle row size of an even number");
  if (n < 0)
    throw new Error('input must be a positive number');

  const numLines = n;
  let spaces = n - 1; 
  let stars = 1;
  const middleLine = Math.floor(numLines/2);

  for(let i = 0; i < numLines; i++) {
    console.log(buildLine(stars, spaces));
    // before the middle line we will increment the number of stars by 2
    if(i < middleLine) {
      stars += 2;
      spaces -= 2;
    }
    // after the middle line we decrement the number of stars by 2
    else {
      stars -= 2;
      spaces += 2;
    }
  }
}

// will build a line with the correct number of stars and spaces
// ie given 3 stars and 2 spaces
// will build ' *** '
function buildLine(stars, spaces) {
  let line = '';
  const lineSize = stars+spaces;

  // the first index in the line with a star.
  const starIndex = Math.floor((lineSize-stars)/2);

  for(let i = 0; i < lineSize; i++) {
    // starts building stars
    if(i >= starIndex && stars > 0) {
      line += '*';
      stars--;
    }
    else
      line += ' ';
  }

  return line;
}

deviated from the spec in one specific way where I don't return null if a an even number or negative number is provided but instead throw an error.
I feel however this gives more information to the user.