EXERCISE · AlgoCasts
Pyramid
Write a function that accepts a positive number N. The function should console log a pyramid shape with N levels using the # character.
Directions
Directions
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#
JS
pyramid(1) '#'pyramid(2) ' # ' '###'pyramid(3) ' # ' ' ### ' '#####'Try it first#
Copy the stub, make the 4 tests pass on your machine, then open the solution. The reveal is remembered per page in this browser.
JSexercises/pyramid/index.js
function pyramid(n) {} module.exports = pyramid;Solution#
JScompleted_exercises/pyramid/index.js
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);} module.exports = pyramid;function pyramid(n) { const midpoint = Math.floor((2 * n - 1) / 2); for (let row = 0; row < n; row++) { let level = ''; for (let column = 0; column < 2 * n - 1; column++) { if (midpoint - row <= column && midpoint + row >= column) { level += '#'; } else { level += ' '; } } console.log(level); }}const pyramid = require('./index'); beforeEach(() => { jest.spyOn(console, 'log');}); afterEach(() => { console.log.mockRestore();}); test('pyramid is a function', () => { expect(typeof pyramid).toEqual('function');}); test('prints a pryamid for n = 2', () => { pyramid(2); expect(console.log.mock.calls[0][0]).toEqual(' # '); expect(console.log.mock.calls[1][0]).toEqual('###'); expect(console.log.mock.calls.length).toEqual(2);}); test('prints a pryamid for n = 3', () => { pyramid(3); expect(console.log.mock.calls[0][0]).toEqual(' # '); expect(console.log.mock.calls[1][0]).toEqual(' ### '); expect(console.log.mock.calls[2][0]).toEqual('#####'); expect(console.log.mock.calls.length).toEqual(3);}); test('prints a pryamid for n = 4', () => { pyramid(4); expect(console.log.mock.calls[0][0]).toEqual(' # '); expect(console.log.mock.calls[1][0]).toEqual(' ### '); expect(console.log.mock.calls[2][0]).toEqual(' ##### '); expect(console.log.mock.calls[3][0]).toEqual('#######'); expect(console.log.mock.calls.length).toEqual(4);}); Verbatim from the repo at 30cf7634. Alternate tabs are the commented-out solutions with the leading // removed and nothing else changed. Run the tests locally with npx jest pyramid inside the fork.
See also