-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
80 lines (73 loc) · 1.72 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
71
72
73
74
75
76
77
78
79
80
export default MyCircularQueue;
type MyCircularQueue<T = any> = {
isEmpty: () => boolean;
Front: () => T | number;
deQueue: () => boolean;
enQueue: (value: T) => boolean;
Rear: () => T | number;
isFull: () => boolean;
capacity: number;
};
function MyCircularQueue<T = any>(capacity = Infinity): MyCircularQueue<T> {
if (capacity < 1) {
throw Error("k greater than or equal one");
}
const storage = new Map<bigint, T>();
let min = BigInt(0);
let max = BigInt(0);
const initial = 0n;
function enQueue(value: T): boolean {
if (isFull()) {
return false;
}
if (storage.size) {
storage.set(max + 1n, value);
max++;
} else {
storage.set(initial, value);
max = initial;
}
return true;
}
function deQueue(): boolean {
if (isEmpty()) {
return false;
} else {
storage.delete(min);
min++;
if (storage.size === 0) {
min = initial;
}
return true;
}
}
function Front(): T | number {
if (isEmpty()) {
return -1;
}
const r = storage.get(min);
return r as T;
}
function isEmpty(): boolean {
return 0 === storage.size;
}
function Rear(): T | number {
if (isEmpty()) {
return -1;
}
const r = storage.get(max);
return r as T;
}
function isFull(): boolean {
return storage.size >= capacity;
}
return {
isEmpty,
Front,
deQueue,
enQueue,
Rear,
isFull,
capacity: capacity,
};
}