Skip to content

Instantly share code, notes, and snippets.

@Luke-Rogerson
Created December 17, 2018 12:24
Show Gist options
  • Save Luke-Rogerson/90986beac11b361e3fc1ca2330f4799a to your computer and use it in GitHub Desktop.
Save Luke-Rogerson/90986beac11b361e3fc1ca2330f4799a to your computer and use it in GitHub Desktop.
Write a function that accepts a positive number N. The function should console log a pyramid shape with N levels using the # character. Make sure the pyramid has spaces on both the left *and* right hand sides
// --- Examples
// pyramid(1)
// '#'
// pyramid(2)
// ' # '
// '###'
// pyramid(3)
// ' # '
// ' ### '
// '#####'
function pyramid(n, row = 0, level = '') {
if (row === n) return;
if (level.length === 2 * n - 1) {
console.log(level);
return pyramid(n, row + 1);
}
const midpoint = Math.floor((2 * n - 1) / 2);
let add;
if (midpoint - row <= level.length && midpoint + row >= level.length) {
add = '#';
} else {
add = ' ';
}
pyramid(n, row, level + add);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment