|
2 | 2 | /** |
3 | 3 | * Simplest Implementation of Stack |
4 | 4 | */ |
5 | | - /* let Stack = function () { |
6 | | - const list = [], |
7 | | - push = data => list.push(data), |
8 | | - pop = () => list.pop(), |
9 | | - size = () => list.length, |
10 | | - viewStack = () => '(bottom) ' + list.join(' -> ') + ' (top)'; |
11 | | - return Object.freeze({ |
12 | | - push, |
13 | | - pop, |
14 | | - size, |
15 | | - viewStack |
16 | | - }); |
17 | | - } |
18 | | - const s = new Stack(); |
19 | | - console.log('push operations'); |
20 | | - s.push(1); // 1 enters in stack |
21 | | - s.push(2); // 2 enters in stack |
22 | | - s.push(3); // 3 enters in stack |
23 | | - |
24 | | - console.log('state of stack is'); |
25 | | - console.log(s.viewStack()); // (bottom) 1 -> 2 -> 3 (top) |
26 | | - |
27 | | - console.log('pop operations'); |
28 | | - console.log(s.pop()); // 3 |
29 | | - console.log(s.pop()); // 2 |
30 | | - console.log(s.pop()); // 1 */ |
| 5 | + /* let Stack = function () { |
| 6 | + const list = [], |
| 7 | + push = data => list.push(data), |
| 8 | + pop = () => list.length > 0 ? list.pop() : undefined, |
| 9 | + size = () => list.length, |
| 10 | + viewStack = () => '(bottom) ' + list.join(' -> ') + ' (top)'; |
| 11 | + return Object.freeze({ |
| 12 | + push, |
| 13 | + pop, |
| 14 | + size, |
| 15 | + viewStack |
| 16 | + }); |
| 17 | + } |
| 18 | + const s = new Stack(); |
| 19 | + console.log('push operations'); |
| 20 | + s.push(1); // 1 enters in stack |
| 21 | + s.push(2); // 2 enters in stack |
| 22 | + s.push(3); // 3 enters in stack |
| 23 | +
|
| 24 | + console.log('state of stack is'); |
| 25 | + console.log(s.viewStack()); // (bottom) 1 -> 2 -> 3 (top) |
| 26 | +
|
| 27 | + console.log('pop operations'); |
| 28 | + console.log(s.pop()); // 3 |
| 29 | + console.log(s.pop()); // 2 |
| 30 | + console.log(s.pop()); // 1 */ |
31 | 31 |
|
32 | 32 | let Stack = function () { |
33 | 33 | const storage = Object.create(null); // key, value pairs |
|
0 commit comments