-
Notifications
You must be signed in to change notification settings - Fork 94
/
index.ts
70 lines (65 loc) · 1.31 KB
/
index.ts
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
import {useMemo} from 'react';
import {useList} from '../useList/index.js';
import {useSyncedRef} from '../useSyncedRef/index.js';
export type QueueMethods<T> = {
/**
* The entire queue.
*/
items: T[];
/**
* The first item in the queue.
*/
first: T | undefined;
/**
* The last item in the queue.
*/
last: T | undefined;
/**
* Adds an item to the end of the queue.
* @param item The item to be added.
*/
add: (item: T) => void;
/**
* Removes and returns the head of the queue.
*/
remove: () => T;
/**
* The current size of the queue.
*/
size: number;
};
/**
* A state hook implementing FIFO queue.
*
* @param initialValue The initial value. Defaults to an empty array.
*/
export function useQueue<T>(initialValue: T[] = []): QueueMethods<T> {
const [list, {removeAt, push}] = useList(initialValue);
const listRef = useSyncedRef(list);
return useMemo(
() => ({
add(value: T) {
push(value);
},
remove() {
const value = listRef.current[0];
removeAt(0);
return value;
},
get first() {
return listRef.current.at(0);
},
get last() {
return listRef.current.at(-1);
},
get size() {
return listRef.current.length;
},
get items() {
return listRef.current;
},
}),
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
}