forked from matrix-org/thirdroom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RecycleBin.ts
45 lines (37 loc) · 1.22 KB
/
RecycleBin.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
import { addHistory, trimHistory, Historian, createHistorian } from "./utils/Historian";
import { obtainFromPool, releaseToPool, Pool, createPool } from "./utils/Pool";
export type RecycleBin<T> = T[];
export interface RecycleBinContext<T> {
active: RecycleBin<T>;
pool: Pool<RecycleBin<T>>;
historian: Historian<RecycleBin<T>>;
}
export function createRecycleBinContext<T>(): RecycleBinContext<T> {
const pool = createPool<RecycleBin<T>>(
() => [],
(item) => (item.length = 0)
);
return {
active: obtainFromPool(pool),
pool,
historian: createHistorian<RecycleBin<T>>(),
};
}
export function addToRecycleBin<T>(recycleCtx: RecycleBinContext<T>, item: T) {
recycleCtx.active.push(item);
}
export function recycleBinNext<T>(recycleCtx: RecycleBinContext<T>, time: number) {
addHistory(recycleCtx.historian, time, recycleCtx.active);
recycleCtx.active = obtainFromPool(recycleCtx.pool);
}
export function recycleBinRelease<T>(
recycleCtx: RecycleBinContext<T>,
lastProcessedTime: number,
cb: (bin: RecycleBin<T>) => void
) {
const trimmed = trimHistory(recycleCtx.historian, lastProcessedTime);
trimmed.forEach((bin) => {
if (cb) cb(bin);
releaseToPool(recycleCtx.pool, bin);
});
}