1 | export class QueueNode {
|
2 | constructor () {
|
3 | /**
|
4 | * @type {QueueNode|null}
|
5 | */
|
6 | this.next = null
|
7 | }
|
8 | }
|
9 |
|
10 | /**
|
11 | * @template V
|
12 | */
|
13 | export class QueueValue extends QueueNode {
|
14 | /**
|
15 | * @param {V} v
|
16 | */
|
17 | constructor (v) {
|
18 | super()
|
19 | this.v = v
|
20 | }
|
21 | }
|
22 |
|
23 | /**
|
24 | * @template {QueueNode} N
|
25 | */
|
26 | export class Queue {
|
27 | constructor () {
|
28 | /**
|
29 | * @type {N | null}
|
30 | */
|
31 | this.start = null
|
32 | /**
|
33 | * @type {N | null}
|
34 | */
|
35 | this.end = null
|
36 | }
|
37 | }
|
38 |
|
39 | /**
|
40 | * @note The queue implementation is experimental and unfinished.
|
41 | * Don't use this in production yet.
|
42 | *
|
43 | * @template {QueueNode} N
|
44 | * @return {Queue<N>}
|
45 | */
|
46 | export const create = () => new Queue()
|
47 |
|
48 | /**
|
49 | * @param {Queue<any>} queue
|
50 | */
|
51 | export const isEmpty = queue => queue.start === null
|
52 |
|
53 | /**
|
54 | * @template {Queue<any>} Q
|
55 | * @param {Q} queue
|
56 | * @param {Q extends Queue<infer N> ? N : never} n
|
57 | */
|
58 | export const enqueue = (queue, n) => {
|
59 | if (queue.end !== null) {
|
60 | queue.end.next = n
|
61 | queue.end = n
|
62 | } else {
|
63 | queue.end = n
|
64 | queue.start = n
|
65 | }
|
66 | }
|
67 |
|
68 | /**
|
69 | * @template {QueueNode} N
|
70 | * @param {Queue<N>} queue
|
71 | * @return {N | null}
|
72 | */
|
73 | export const dequeue = queue => {
|
74 | const n = queue.start
|
75 | if (n !== null) {
|
76 | // @ts-ignore
|
77 | queue.start = n.next
|
78 | if (queue.start === null) {
|
79 | queue.end = null
|
80 | }
|
81 | return n
|
82 | }
|
83 | return null
|
84 | }
|