-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.js
46 lines (44 loc) · 1.17 KB
/
pool.js
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
//@ts-check
/**
* @template ItemType
* @name Pool<ItemType>
*/
class Pool {
constructor() {
/**@type {Map<symbol,ItemType>} */
this.pool = new Map();
}
/**@param {ItemType} item */
add(item) {
const itemID = Symbol();
this.pool.set(itemID, item);
return itemID;
}
/**@param {symbol} itemID */
remove(itemID) {
this.pool.delete(itemID);
return;
}
/**
* @param {(item:ItemType)=>boolean} matcherFunction
* @returns {ItemType | void}
*/
findSync(matcherFunction) {
const allItems = this.pool.values();
for (let item of allItems) {
if (matcherFunction(item)) return item;
}
}
/**
* @param {(item:ItemType)=>Promise<boolean>} asyncMatcherFunction
* @returns {Promise<void | ItemType>} - Resolves `void` if no item matches.
*/
async find(asyncMatcherFunction) {
const allItems = this.pool.values();
for (let item of allItems) {
if (await asyncMatcherFunction(item))
return item;
}
}
}
exports = module.exports = Pool;