The challenge
Write a function that when given a number >= 0, returns an Array of ascending length subarrays.
pyramid(0) => [ ]
pyramid(1) => [ [1] ]
pyramid(2) => [ [1], [1, 1] ]
pyramid(3) => [ [1], [1, 1], [1, 1, 1] ]
Note: the subarrays should be filled with 1
s
The solution in Javascript
Option 1:
function pyramid(n) {
const res = [];
for(let i = 0; i < n; i++){
res.push([...Array(i+1)].fill(1))
}
return res;
}
Option 2:
function pyramid(n) {
return Array(n).fill().map((e,i)=>Array(i+1).fill(1))
}
Option 3:
const pyramid = n => Array(n).fill(1).map((x, i) => Array(i + 1).fill(1))
Test cases to validate our solution
describe('basic tests', () => {
it("Testing for 0", () => assert.deepEqual(pyramid(0), []));
it("Testing for 1", () => assert.deepEqual(pyramid(1), [[1]]));
it("Testing for 2", () => assert.deepEqual(pyramid(2), [[1], [1, 1]]));
it("Testing for 3", () => assert.deepEqual(pyramid(3), [[1], [1, 1], [1, 1, 1]]));
});