-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
queue.js
84 lines (78 loc) · 1.31 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
84
export class QueueNode {
constructor () {
/**
* @type {QueueNode|null}
*/
this.next = null
}
}
/**
* @template V
*/
export class QueueValue extends QueueNode {
/**
* @param {V} v
*/
constructor (v) {
super()
this.v = v
}
}
/**
* @template {QueueNode} N
*/
export class Queue {
constructor () {
/**
* @type {N | null}
*/
this.start = null
/**
* @type {N | null}
*/
this.end = null
}
}
/**
* @note The queue implementation is experimental and unfinished.
* Don't use this in production yet.
*
* @template {QueueNode} N
* @return {Queue<N>}
*/
export const create = () => new Queue()
/**
* @param {Queue<any>} queue
*/
export const isEmpty = queue => queue.start === null
/**
* @template {Queue<any>} Q
* @param {Q} queue
* @param {Q extends Queue<infer N> ? N : never} n
*/
export const enqueue = (queue, n) => {
if (queue.end !== null) {
queue.end.next = n
queue.end = n
} else {
queue.end = n
queue.start = n
}
}
/**
* @template {QueueNode} N
* @param {Queue<N>} queue
* @return {N | null}
*/
export const dequeue = queue => {
const n = queue.start
if (n !== null) {
// @ts-ignore
queue.start = n.next
if (queue.start === null) {
queue.end = null
}
return n
}
return null
}