-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.js
83 lines (68 loc) · 1.38 KB
/
queue.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
const Node = require('../node/node')
const { Iterator } = require('../../abstracts')
/**
* Queue
* @classdesc Generic Queue implementation based on linked-lists.
* @implements {Iterator}
* @see p. 151, 155
*/
class Queue {
constructor () {
this._n = 0
this._first = null
this._last = null
Object.seal(this)
}
/**
* Returns if the Queue is empty
*/
isEmpty () {
return this._first === null
}
/**
* Returns the Queue's size
*/
size () {
return this._n
}
/**
* Inserts an item to the end of the Queue
* @param {*} item The item to be stored
*/
enqueue (item) {
const oldLast = this._last
this._last = new Node()
this._last._item = item
this._last._next = null
if (this.isEmpty()) {
this._first = this._last
} else {
oldLast._next = this._last
}
this._n++
}
/**
* Removes and returns the first item
* inserted to the Queue.
*/
dequeue () {
if (this.isEmpty()) {
throw new ReferenceError('queue is empty')
}
const removedItem = this._first._item
this._first = this._first._next
this._n--
if (this.isEmpty()) {
this._last = null
}
return removedItem
}
/**
* Returns an Iterator to traverse the Queue.
* @returns {Iterator}
*/
[Symbol.iterator] () {
return new Iterator(this._first)
}
}
module.exports = Queue