Created
December 17, 2018 12:24
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// --- 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