DEV Community

Discussion on: Daily Challenge #2 - String Diamond

Collapse
 
lucasromerodb profile image
Luke • Edited

JS

const drawRow = (qty, replaceWith) => {
  let str = "";
  for (let i = 0; i < qty; i++) {
    str += replaceWith;
  }

  return str;
};

const printDiamond = (n) => {
  if (n % 2 === 0 || n < 0) {
    return "The number should be odd and positive";
  }

  let row = "";
  let stars = 0;

  for (let i = 0; i < n; i++) {
    if (i > parseInt(n / 2)) {
      stars -= 2;
    } else {
      stars = i * 2 + 1;
    }

    const spaces = (n - stars) / 2;

    row += drawRow(spaces, " ");
    row += drawRow(stars, "*");
    row += drawRow(spaces, " ");

    if (i !== n - 1) {
      row += "\n";
    }
  }

  return row;
};

console.log(printDiamond(11));