-
Notifications
You must be signed in to change notification settings - Fork 929
/
stack.js
69 lines (61 loc) · 1.26 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
const LinkedList = require('../linked-lists/linked-list');
// tag::constructor[]
/**
* Data structure that adds and remove elements in a first-in, first-out (FIFO) fashion
*/
class Stack {
constructor() {
this.items = new LinkedList();
}
// end::constructor[]
// tag::add[]
/**
* Add element into the stack. Similar to Array.push
* Runtime: O(1)
* @param {any} item
* @returns {stack} instance to allow chaining.
*/
add(item) {
this.items.addLast(item);
return this;
}
// end::add[]
// tag::remove[]
/**
* Remove element from the stack.
* Similar to Array.pop
* Runtime: O(1)
* @returns {any} removed value.
*/
remove() {
return this.items.removeLast();
}
// end::remove[]
/**
* Size of the queue
*/
get size() {
return this.items.size;
}
/**
* Return true if is empty false otherwise true
*/
isEmpty() {
return !this.items.size;
}
}
// aliases
Stack.prototype.push = Stack.prototype.add;
Stack.prototype.pop = Stack.prototype.remove;
module.exports = Stack;
/* Usage Example:
// tag::snippet[]
const stack = new Stack();
stack.add('a');
stack.add('b');
stack.remove(); //↪️ b
stack.add('c');
stack.remove(); //↪️ c
stack.remove(); //↪️ a
// end::snippet[]
// */