EXERCISE · AlgoCasts
Steps
Write a function that accepts a positive number N. The function should console log a step shape with N levels using the # character.
Directions
Directions
Write a function that accepts a 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!
Examples#
JS
steps(2) '# ' '##'steps(3) '# ' '## ' '###'steps(4) '# ' '## ' '### ' '####'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/steps/index.js
function steps(n) {} module.exports = steps;Solution#
JScompleted_exercises/steps/index.js
function steps(n, row = 0, stair = '') { if (n === row) { return; } if (n === stair.length) { console.log(stair); return steps(n, row + 1); } const add = stair.length <= row ? '#' : ' '; steps(n, row, stair + add);} module.exports = steps;function steps(n) { for (let row = 0; row < n; row++) { let stair = ''; for (let column = 0; column < n; column++) { if (column <= row) { stair += '#'; } else { stair += ' '; } } console.log(stair); }}const steps = require('./index'); beforeEach(() => { jest.spyOn(console, 'log');}); afterEach(() => { console.log.mockRestore();}); test('steps is a function', () => { expect(typeof steps).toEqual('function');}); test('steps called with n = 1', () => { steps(1); expect(console.log.mock.calls[0][0]).toEqual('#'); expect(console.log.mock.calls.length).toEqual(1);}); test('steps called with n = 2', () => { steps(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('steps called with n = 3', () => { steps(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);}); 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 steps inside the fork.
See also