Skip to content

Commit 6a0bd77

Browse files
Implement a solution to build a piramid with n levels, write tests
1 parent 2d4eaae commit 6a0bd77

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

10_pyramid/index.js

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// --- Directions
2+
// Write a function that accepts a positive number N.
3+
// The function should console log a pyramid shape
4+
// with N levels using the # character. Make sure the
5+
// pyramid has spaces on both the left *and* right hand sides
6+
// --- Examples
7+
// pyramid(1)
8+
// '#'
9+
// pyramid(2)
10+
// ' # '
11+
// '###'
12+
// pyramid(3)
13+
// ' # '
14+
// ' ### '
15+
// '#####'
16+
17+
// Solution 1
18+
// function pyramid(n) {
19+
// const midPoint = Math.floor((2 * n - 1)/2)
20+
// for(let row = 0; row < n; row++) {
21+
// let level = '';
22+
// for(let column = 0; column < 2*n - 1; column++) {
23+
// if(midPoint - row <= column && midPoint + row >=column) {
24+
// level += '#'
25+
// } else {
26+
// level += ' '
27+
// }
28+
// }
29+
// console.log(level);
30+
// }
31+
// }
32+
33+
// Solution 2
34+
function pyramid(n, row = 0, str = "") {
35+
if (n === row) {
36+
return;
37+
}
38+
const midPoint = Math.floor((2 * n - 1) / 2)
39+
if (str.length === 2 * n - 1) {
40+
console.log(str);
41+
return pyramid(n, row + 1)
42+
} else {
43+
if (midPoint - row <= str.length && midPoint + row >= str.length) {
44+
str += '#'
45+
} else {
46+
str += ' '
47+
}
48+
return pyramid(n, row, str)
49+
}
50+
}
51+
52+
module.exports = pyramid;

10_pyramid/test.js

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
const pyramid = require('./index');
2+
3+
beforeEach(() => {
4+
jest.spyOn(console, 'log');
5+
});
6+
7+
afterEach(() => {
8+
console.log.mockRestore();
9+
});
10+
11+
test('pyramid is a function', () => {
12+
expect(typeof pyramid).toEqual('function');
13+
});
14+
15+
test('prints a pryamid for n = 2', () => {
16+
pyramid(2);
17+
expect(console.log.mock.calls[0][0]).toEqual(' # ');
18+
expect(console.log.mock.calls[1][0]).toEqual('###');
19+
expect(console.log.mock.calls.length).toEqual(2);
20+
});
21+
22+
test('prints a pryamid for n = 3', () => {
23+
pyramid(3);
24+
expect(console.log.mock.calls[0][0]).toEqual(' # ');
25+
expect(console.log.mock.calls[1][0]).toEqual(' ### ');
26+
expect(console.log.mock.calls[2][0]).toEqual('#####');
27+
expect(console.log.mock.calls.length).toEqual(3);
28+
});
29+
30+
test('prints a pryamid for n = 4', () => {
31+
pyramid(4);
32+
expect(console.log.mock.calls[0][0]).toEqual(' # ');
33+
expect(console.log.mock.calls[1][0]).toEqual(' ### ');
34+
expect(console.log.mock.calls[2][0]).toEqual(' ##### ');
35+
expect(console.log.mock.calls[3][0]).toEqual('#######');
36+
expect(console.log.mock.calls.length).toEqual(4);
37+
});

0 commit comments

Comments
 (0)