Pyramid v2
Write a function that accepts positive number N. The function should console log a step shape with N levels using the # character. Make sure the step has spaces on the right hand side.
Example:
console.log(pyramid(5))
“ # “
“ ### “
“ ##### “
“ ####### “
“#########”
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);
}
console.log(pyramid(5))
First we create function in our case pyramid with only one parameter named n, row = 0 and level = ‘’
We check if row === n and if true we return and stop calling pyramid.
If the level.length === 2 n - 1 we return the pyramid(n,row+1) so this is when we check when our string has length of 2 * n - 1;
We create a variable midpoint where we calculate with Math.floor(( 2* n-1 ) / 2) that will give us midpoint index.
We have if statement where we check if **midpoint* - row <= level.lenght && midpoint + row >= level.length*; And if true we assing temporary variable *add will be concatinated with ‘#’ sign else add will be concatinated with empty string
After that we start our next call of pyramid where we call pyramid (n, row,level + add)