-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathStorageBox.ts
111 lines (99 loc) · 2.59 KB
/
StorageBox.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/**
* A cache that holds data
* @param Limit
* @param sweepInterval
* @param sweepFilter
* @extends Map
*/
export class StorageBox<K, V> extends Map<K, V> {
public limit: number;
sweepInterval: number;
sweepFilter: (v: V) => boolean
constructor(limit: number = 1000, sweepInterval?: number, sweepFilter?: (v: V) => boolean) {
super();
this.limit = limit
this.sweepInterval = sweepInterval || null
this.sweepFilter = sweepFilter || null
if (this.sweepInterval) this.sweep()
}
/**
* Filters out items from the Cache that matches the function
* @param func
* @returns An Array of the filtered items
*/
public filter(func: (item: V) => boolean): V[] {
const arr = [];
for (const item of this.values()) {
if (func(item)) {
arr.push(item);
}
}
return arr;
}
/**
* Find something from the cache
* @param func
* @returns
*/
public find(func: (item: V) => boolean) {
for (const item of this.values()) {
if (func(item)) {
return item;
}
}
return undefined;
}
/**
* @returns The first value of the cache
*/
public first(): V | V[] {
for (const item of this.values()) {
return item
}
}
/**
* @returns All values in an Array
*/
public getAll() {
return Array.from(this.values())
}
/**
* @returns A random Value
*/
public random(): V | undefined {
return this.size ? Array.from(this.values())[Math.floor(Math.random() * this.size)] : undefined
}
/**
* Maps all The Data in an Array
* @param func
* @returns An Array
*/
public map(func: (item: V) => boolean) {
const arr = [];
for (const item of this.values()) {
arr.push(func(item));
}
return arr;
}
public set(key: K, value: V): this {
if (this.limit === 0) return this
else if (this.size >= this.limit) return this
return super.set(key, value);
}
public some(func: (item: V) => boolean) {
for (const item of this.values()) {
if (func(item)) {
return true;
}
}
return false;
}
private sweep() {
setInterval(() => {
this.forEach((value, key) => {
if (this.sweepFilter && !this.sweepFilter(value)) this.delete(key)
else this.clear()
})
}, this.sweepInterval)
}
}