File tree Expand file tree Collapse file tree 2 files changed +74
-0
lines changed Expand file tree Collapse file tree 2 files changed +74
-0
lines changed Original file line number Diff line number Diff line change 1+ // Option 1
2+ export const steps = ( n : number ) => {
3+ for ( let row = 0 ; row < n ; row ++ ) {
4+ let stair = '' ;
5+
6+ for ( let column = 0 ; column < n ; column ++ ) {
7+ if ( column <= row ) {
8+ stair += '#' ;
9+ } else {
10+ stair += ' ' ;
11+ }
12+ }
13+
14+ console . log ( stair ) ;
15+ }
16+ } ;
17+
18+ // Option 2
19+ export const stepsWithRecursion = ( n : number , row = 0 , stair = '' ) => {
20+ if ( n === row ) {
21+ return ;
22+ }
23+
24+ if ( n === stair . length ) {
25+ console . log ( stair ) ;
26+ return stepsWithRecursion ( n , row + 1 ) ;
27+ }
28+
29+ const add = stair . length <= row ? '#' : ' ' ;
30+ stepsWithRecursion ( n , row , stair + add ) ;
31+ } ;
Original file line number Diff line number Diff line change 1+ import { SpyInstance , describe , test , vi } from 'vitest' ;
2+ import { steps , stepsWithRecursion } from '../steps' ;
3+
4+ describe ( 'Steps Algorithm' , ( ) => {
5+ let spy : SpyInstance ;
6+
7+ beforeEach ( ( ) => {
8+ spy = vi . spyOn ( console , 'log' ) . mockImplementation ( ( ) => { } ) ;
9+ } ) ;
10+
11+ afterEach ( ( ) => {
12+ spy . mockRestore ( ) ;
13+ } ) ;
14+
15+ test ( 'steps is a function' , ( ) => {
16+ expect ( typeof steps ) . toEqual ( 'function' ) ;
17+ expect ( typeof stepsWithRecursion ) . toEqual ( 'function' ) ;
18+ } ) ;
19+
20+ test ( 'steps called with n = 1' , ( ) => {
21+ steps ( 1 ) ;
22+ stepsWithRecursion ( 1 ) ;
23+ expect ( spy . mock . calls [ 0 ] [ 0 ] ) . toEqual ( '#' ) ;
24+ expect ( spy . mock . calls . length ) . toEqual ( 2 ) ;
25+ } ) ;
26+
27+ test ( 'steps called with n = 2' , ( ) => {
28+ steps ( 2 ) ;
29+ stepsWithRecursion ( 2 ) ;
30+ expect ( spy . mock . calls [ 0 ] [ 0 ] ) . toEqual ( '# ' ) ;
31+ expect ( spy . mock . calls [ 1 ] [ 0 ] ) . toEqual ( '##' ) ;
32+ expect ( spy . mock . calls . length ) . toEqual ( 4 ) ;
33+ } ) ;
34+
35+ test ( 'steps called with n = 3' , ( ) => {
36+ steps ( 3 ) ;
37+ stepsWithRecursion ( 3 ) ;
38+ expect ( spy . mock . calls [ 0 ] [ 0 ] ) . toEqual ( '# ' ) ;
39+ expect ( spy . mock . calls [ 1 ] [ 0 ] ) . toEqual ( '## ' ) ;
40+ expect ( spy . mock . calls [ 2 ] [ 0 ] ) . toEqual ( '###' ) ;
41+ expect ( spy . mock . calls . length ) . toEqual ( 6 ) ;
42+ } ) ;
43+ } ) ;
You can’t perform that action at this time.
0 commit comments