Skip to content

Commit 7b13ce8

Browse files
feat: fizzbuzz algorithm
1 parent 7fea232 commit 7b13ce8

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/algorithms/fizzbuzz/fizzbuzz.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
export const fizzBuzz = (n: number) => {
2+
for (let i = 1; i <= n; i++) {
3+
if (i % 3 === 0 && i % 5 === 0) {
4+
console.log('FizzBuzz');
5+
} else if (i % 3 === 0) {
6+
console.log('Fizz');
7+
} else if (i % 5 === 0) {
8+
console.log('Buzz');
9+
} else {
10+
console.log(i);
11+
}
12+
}
13+
};
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { SpyInstance, describe, test, vi } from 'vitest';
2+
3+
import { fizzBuzz } from '../fizzbuzz';
4+
5+
describe('Fizzbuzz Algorithm', () => {
6+
let spy: SpyInstance;
7+
8+
beforeEach(() => {
9+
spy = vi.spyOn(console, 'log').mockImplementation(() => {});
10+
});
11+
12+
afterEach(() => {
13+
spy.mockRestore();
14+
});
15+
16+
test('fizzBuzz function is defined', () => {
17+
expect(fizzBuzz).toBeDefined();
18+
});
19+
20+
test('Calling fizzbuzz with `5` prints out 5 statements', () => {
21+
fizzBuzz(5);
22+
23+
expect(spy.mock.calls.length).toEqual(5);
24+
});
25+
26+
test('Calling fizzbuzz with 15 prints out the correct values', () => {
27+
fizzBuzz(15);
28+
29+
expect(spy.mock.calls[0][0]).toEqual(1);
30+
expect(spy.mock.calls[1][0]).toEqual(2);
31+
expect(spy.mock.calls[2][0]).toEqual('Fizz');
32+
expect(spy.mock.calls[3][0]).toEqual(4);
33+
expect(spy.mock.calls[4][0]).toEqual('Buzz');
34+
expect(spy.mock.calls[5][0]).toEqual('Fizz');
35+
expect(spy.mock.calls[6][0]).toEqual(7);
36+
expect(spy.mock.calls[7][0]).toEqual(8);
37+
expect(spy.mock.calls[8][0]).toEqual('Fizz');
38+
expect(spy.mock.calls[9][0]).toEqual('Buzz');
39+
expect(spy.mock.calls[10][0]).toEqual(11);
40+
expect(spy.mock.calls[11][0]).toEqual('Fizz');
41+
expect(spy.mock.calls[12][0]).toEqual(13);
42+
expect(spy.mock.calls[13][0]).toEqual(14);
43+
expect(spy.mock.calls[14][0]).toEqual('FizzBuzz');
44+
});
45+
});

0 commit comments

Comments
 (0)