Skip to content

Commit

Permalink
feat: staircase steps algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
francislagares committed Aug 18, 2023
1 parent 49522ad commit 7e0a512
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/algorithms/steps/steps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Option 1
export const steps = (n: number) => {
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);
}
};

// Option 2
export const stepsWithRecursion = (n: number, row = 0, stair = '') => {
if (n === row) {
return;
}

if (n === stair.length) {
console.log(stair);
return stepsWithRecursion(n, row + 1);
}

const add = stair.length <= row ? '#' : ' ';
stepsWithRecursion(n, row, stair + add);
};
43 changes: 43 additions & 0 deletions src/algorithms/steps/tests/steps.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { SpyInstance, describe, test, vi } from 'vitest';
import { steps, stepsWithRecursion } from '../steps';

describe('Steps Algorithm', () => {
let spy: SpyInstance;

beforeEach(() => {
spy = vi.spyOn(console, 'log').mockImplementation(() => {});
});

afterEach(() => {
spy.mockRestore();
});

test('steps is a function', () => {
expect(typeof steps).toEqual('function');
expect(typeof stepsWithRecursion).toEqual('function');
});

test('steps called with n = 1', () => {
steps(1);
stepsWithRecursion(1);
expect(spy.mock.calls[0][0]).toEqual('#');
expect(spy.mock.calls.length).toEqual(2);
});

test('steps called with n = 2', () => {
steps(2);
stepsWithRecursion(2);
expect(spy.mock.calls[0][0]).toEqual('# ');
expect(spy.mock.calls[1][0]).toEqual('##');
expect(spy.mock.calls.length).toEqual(4);
});

test('steps called with n = 3', () => {
steps(3);
stepsWithRecursion(3);
expect(spy.mock.calls[0][0]).toEqual('# ');
expect(spy.mock.calls[1][0]).toEqual('## ');
expect(spy.mock.calls[2][0]).toEqual('###');
expect(spy.mock.calls.length).toEqual(6);
});
});

0 comments on commit 7e0a512

Please sign in to comment.