PriorityQueue.js
1.4 KB
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
'use strict'
const Queue = require('./Queue')
/**
* @class
* @private
*/
class PriorityQueue {
constructor (size) {
this._size = Math.max(+size | 0, 1)
this._slots = []
// initialize arrays to hold queue elements
for (let i = 0; i < this._size; i++) {
this._slots.push(new Queue())
}
}
get length () {
let _length = 0
for (let i = 0, slots = this._slots.length; i < slots; i++) {
_length += this._slots[i].length
}
return _length
}
enqueue (obj, priority) {
// Convert to integer with a default value of 0.
priority = priority && +priority | 0 || 0
if (priority) {
if (priority < 0 || priority >= this._size) {
priority = (this._size - 1)
// put obj at the end of the line
}
}
this._slots[priority].push(obj)
}
dequeue () {
for (let i = 0, sl = this._slots.length; i < sl; i += 1) {
if (this._slots[i].length) {
return this._slots[i].shift()
}
}
return
}
get head () {
for (let i = 0, sl = this._slots.length; i < sl; i += 1) {
if (this._slots[i].length > 0) {
return this._slots[i].head
}
}
return
}
get tail () {
for (let i = this._slots.length - 1; i >= 0; i--) {
if (this._slots[i].length > 0) {
return this._slots[i].tail
}
}
return
}
}
module.exports = PriorityQueue