-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.js
98 lines (84 loc) · 1.88 KB
/
Stack.js
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import StackNode from "./StackNode.js";
export default class Stack {
/**
* Builds a stack
*/
constructor() {
/** @var StackNode */
this.head = null;
/** @var Number */
this.size = 0;
}
/**
* Pushes a new Stack Node into this stack.
* @param {any} value Value to push
* @returns {Stack} This stack
*/
push(value) {
const node = new StackNode(value, this.head);
this.head = node;
this.size++;
return this;
}
/**
* Pops out the Stack Node at the top of this stack.
* @returns {(StackNode|null)}
*/
pop() {
if (!this.head) return null;
const poppedNode = this.head;
this.head = this.head.next;
poppedNode.next = null;
this.size--;
return poppedNode.value;
}
/**
* This stack's size
* @returns {Number}
*/
length() {
return this.size;
}
/**
* Returns the value of this stack's head
* @returns {any}
*/
peek() {
if (!this.head) return null;
return this.head.value;
}
/**
* Determines if this stack is empty.
* @returns {boolean}
*/
isEmpty() {
return this.head === null;
}
/**
* Represents this stack as an array of either its nodes or nodes values
* @param {boolean} value false for getting the node instead
* @returns {(StackNode|any)}
*/
toArray(value = true) {
const nodes = [];
let currentNode = this.head;
while (currentNode) {
var v = currentNode;
if (value) v = currentNode.value;
nodes.push(v);
currentNode = currentNode.next;
}
return nodes;
}
/**
* Returns a string representation of this stack nodes separated by commas.
* @param {function} stringifierFn Custom stringifier function
* @returns {string}
*/
toString(stringifierFn) {
if (!this.head) return "";
return this.toArray(false)
.map((n) => n.toString(stringifierFn))
.toString();
}
}