MCPcopy Create free account
hub / github.com/bradtraversy/javascript-sandbox / Stack

Class Stack

17-iterators-data-structures/08-stacks/script.js:1–48  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class Stack {
2 constructor() {
3 this._items = [];
4 this._count = 0;
5 }
6
7 push(item) {
8 this._items[this._count] = item;
9 this._count++;
10 }
11
12 pop() {
13 if (this.isEmpty()) {
14 return 'Underflow';
15 }
16
17 const item = this._items[this._count - 1];
18 this._count--;
19
20 for (let i = this._count; i < this._items.length; i++) {
21 this._items[i] = this._items[i + 1];
22 }
23
24 this._items.length = this._count;
25 return item;
26 }
27
28 peek() {
29 if (this.isEmpty()) {
30 return 'No items in stack';
31 }
32
33 return this._items[this._count - 1];
34 }
35
36 isEmpty() {
37 return this._count === 0;
38 }
39
40 length() {
41 return this._count;
42 }
43
44 clear() {
45 this._items = [];
46 this._count = 0;
47 }
48}
49
50const stack = new Stack();
51

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected