File tree Expand file tree Collapse file tree 3 files changed +107
-0
lines changed
Expand file tree Collapse file tree 3 files changed +107
-0
lines changed Original file line number Diff line number Diff line change 1+ # 0003 Stack ( L-I )
2+
3+ ## Problem
4+
5+ Create a class that has 3 method and 1 property.
6+
7+ - Push method add new element to the stack
8+ - Pop method remove last added element and return removed element
9+ - Peek return last added element
10+ - Size property return stack size
11+
12+ ## Solution
13+
14+ ``` javascript
15+ class Stack {
16+ constructor () {
17+ this .stack = []
18+ }
19+
20+ push (value ) {
21+ this .stack .push (value)
22+ }
23+
24+ pop () {
25+ return this .stack .pop ()
26+ }
27+
28+ peek () {
29+ return this .stack .at (- 1 )
30+ }
31+
32+ get size () {
33+ return this .stack .length
34+ }
35+ }
36+ ```
37+
38+ ## References
39+
40+ - [ Class MDN] ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes )
41+ - [ Stack GeeksForGeeks] ( https://www.geeksforgeeks.org/implementation-stack-javascript/ )
42+ - [ Array MDN] ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array )
43+
44+ ## Problem Added By
45+
46+ - [ GitHub] ( https://www.github.com/kennarddh )
47+
48+ ## Contributing
49+
50+ Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
51+
52+ Please make sure to update tests as appropriate.
Original file line number Diff line number Diff line change 1+ class Stack {
2+ constructor ( ) {
3+ this . stack = [ ]
4+ }
5+
6+ push ( value ) {
7+ this . stack . push ( value )
8+ }
9+
10+ pop ( ) {
11+ return this . stack . pop ( )
12+ }
13+
14+ peek ( ) {
15+ return this . stack . at ( - 1 )
16+ }
17+
18+ get size ( ) {
19+ return this . stack . length
20+ }
21+ }
22+
23+ module . exports = Stack
Original file line number Diff line number Diff line change 1+ const { strict : assert } = require ( 'assert' )
2+
3+ const Stack = require ( './Stack.js' )
4+
5+ const stack = new Stack ( )
6+
7+ stack . push ( 'foo' )
8+
9+ assert . equal ( stack . size , 1 )
10+
11+ stack . push ( 'bar' )
12+
13+ assert . equal ( stack . size , 2 )
14+
15+ assert . equal ( stack . peek ( ) , 'bar' )
16+ assert . equal ( stack . size , 2 )
17+ assert . equal ( stack . pop ( ) , 'bar' )
18+ assert . equal ( stack . size , 1 )
19+ assert . equal ( stack . peek ( ) , 'foo' )
20+ assert . equal ( stack . size , 1 )
21+
22+ stack . push ( 'foobar' )
23+
24+ assert . equal ( stack . size , 2 )
25+ assert . equal ( stack . peek ( ) , 'foobar' )
26+ assert . equal ( stack . size , 2 )
27+ assert . equal ( stack . pop ( ) , 'foobar' )
28+ assert . equal ( stack . size , 1 )
29+ assert . equal ( stack . pop ( ) , 'foo' )
30+ assert . equal ( stack . size , 0 )
31+
32+ console . log ( 'All tests success' )
You can’t perform that action at this time.
0 commit comments