Skip to content

Instantly share code, notes, and snippets.

@Lumexralph
Last active September 28, 2020 12:25
Show Gist options
  • Save Lumexralph/f28603800148e36ed57848a99446a74c to your computer and use it in GitHub Desktop.
Save Lumexralph/f28603800148e36ed57848a99446a74c to your computer and use it in GitHub Desktop.
Write the implementation of the diamond function. The single parameter passed // in is the width of the diamond. Even numbers don't generate beautiful // diamonds, nor do negative ones, so return an empty string in those cases.
const diamond = (n) => {
// your solution
// weed out negative and even numbers
if (n <= 0 || n % 2 == 0) return "";
let k = 0; // to create the count pattern
let row = parseInt((n + 1) / 2);
let diamondStructure = [];
const space = " ";
const star = "*";
for (let i = 1; i <= n; i++) {
// if we get to the row, we should count down
i <= row ? k++ : k--;
const spaceCount = row - k;
const starCount = n - 2 * spaceCount;
const diamondLayer = space.repeat(spaceCount) + star.repeat(starCount) + space.repeat(spaceCount);
diamondStructure.push(diamondLayer);
}
const diamond = diamondStructure.join("\n");
return "\n" + diamond + "\n"; // pad with newline
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment