-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.js
71 lines (59 loc) · 1.19 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
const Node = require('../node/node')
const { Iterator } = require('../../abstracts')
/**
* Stack
* @classdesc Generic Stack implementation based on linked-lists.
* @implements {Iterator}
* @see p. 147, 149, 155
*/
class Stack {
constructor () {
this._n = 0
this._first = null
Object.seal(this)
}
/**
* Returns if the Stack is empty
*/
isEmpty () {
return this._first === null
}
/**
* Returns the Stacks' size
*/
size () {
return this._n
}
/**
* Inserts an item to the Stack
* @param {*} item The item to be stored
*/
push (item) {
const oldFirst = this._first
this._first = new Node()
this._first._item = item
this._first._next = oldFirst
this._n++
}
/**
* Removes and returns the last inserted
* item from the Stack.
*/
pop () {
if (this.isEmpty()) {
throw new ReferenceError('stack is empty')
}
const removedItem = this._first._item
this._first = this._first._next
this._n--
return removedItem
}
/**
* Returns an Iterator to traverse the stack.
* @returns {Iterator}
*/
[Symbol.iterator] () {
return new Iterator(this._first)
}
}
module.exports = Stack