-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresizable-array-stack.js
91 lines (74 loc) · 1.88 KB
/
resizable-array-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
const assert = require('assert')
const { ReversedArrayIterator } = require('../../abstracts')
/**
* ResizableArrayStack
* @classdesc A Resizable Generic Array Stack.
* @implements {ReversedArrayIterator}
* @see p. 141
*/
class ResizableArrayStack {
constructor () {
this._a = new Array(1) // it should start with length of 1
this._n = 0
Object.seal(this)
}
/**
* Returns if the Stack is empty.
* @returns {boolean} Whether the stack is empty or not.
*/
isEmpty () {
return this._n === 0
}
/**
* Returns the number of the elements in the stack.
* @returns {number} Stack's size.
*/
size () {
return this._n
}
/**
* Resizes the internal array `_a` copying the elements from [0, _n)
* @param {number} max New size for the internal array in the stack.
*/
resize (max) {
assert(max, `max is required. Given: ${max}`)
const temp = new Array(max)
for (let i = 0; i < this._n; i++) {
temp[i] = this._a[i]
}
this._a = temp
}
/**
* Inserts an item to the Stack.
* @param {*} item The item to be stored
*/
push (item) {
if (this._n === this._a.length) {
this.resize(2 * this._n)
}
this._a[this._n++] = item
}
/**
* Removes and returns the last item inserted in the Stack.
* @returns {*} The item at the top of the Stack.
*/
pop () {
if (this.isEmpty()) {
throw new ReferenceError('stack is empty')
}
const item = this._a[--this._n]
this._a[this._n] = undefined // avoid loitering
if (this._n > 0 && this._n === Math.floor(this._a.length / 4)) {
this.resize(Math.floor(this._a.length / 2))
}
return item
}
/**
* Returns an Iterator to traverse the stack.
* @returns {ReversedArrayIterator}
*/
[Symbol.iterator] () {
return new ReversedArrayIterator(this._a, this._n)
}
}
module.exports = ResizableArrayStack