-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathstack.js
More file actions
75 lines (65 loc) · 1.76 KB
/
stack.js
File metadata and controls
75 lines (65 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// src/04-stack/stack.js
// @ts-ignore
class Stack {
// private property
#items = []; // {1}
/**
* Adds a new element to the top of the stack
* @param {*} item - new element to be added to the stack
*/
push(item) {
this.#items.push(item);
}
/**
* Removes the top element from the stack and returns it. If the stack is empty, undefined is returned and the stack is not modified.
*/
pop() {
return this.#items.pop();
}
/**
* Returns the top element of the stack without removing it. The stack is not modified (it does not remove the element; it only returns the element for information purposes).
*/
peek() {
return this.#items[this.#items.length - 1];
}
/**
* Returns true if the stack does not contain any elements and false if the size of the stack is bigger than 0.
*/
isEmpty() {
return this.#items.length === 0;
}
/**
* Returns the number of elements in the stack. It is similar to the length property of an array.
*/
get size() {
return this.#items.length;
}
/**
* Removes all the elements from the stack
*/
clear() {
/* while (!this.isEmpty()) {
this.pop();
} */
this.#items = [];
}
/**
* Returns a string representation of the stack, bottom to top, without modifying the stack
*/
toString() {
if (this.isEmpty()) {
return 'Empty Stack';
} else {
return this.#items.map(item => { // {1}
if (typeof item === 'object' && item !== null) { // {2}
return JSON.stringify(item); // Handle objects
} else {
return item.toString(); // Handle other types {3}
}
}).join(', '); // {4}
}
}
}
// export node module so it can be used in different files
// CommonJS export
module.exports = Stack;