-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcombineTokens.ts
34 lines (29 loc) · 1.04 KB
/
combineTokens.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
import {getRandomInt} from '../number/index.js';
export interface CombinationToken {
token: string;
/** return `true` to include in selection pool for iteration. */
filterFn?: (index: number, spent: number, generated: string[]) => boolean;
}
const kDefaultFilterFn = () => true;
export function combineTokens(tokens: CombinationToken[], count: number) {
const spentRecord: Record<string, number | undefined> = {};
const result: string[] = [];
const getAvailableTokens = (index: number) => {
return tokens.filter(token => {
const spent = spentRecord[token.token] || 0;
const filterFn = token.filterFn || kDefaultFilterFn;
return filterFn(index, spent, result);
});
};
for (
let i = 0, available = getAvailableTokens(i);
i < count && available.length > 0;
i++, available = getAvailableTokens(i)
) {
const index = getRandomInt(0, available.length);
const token = available[index];
spentRecord[token.token] = (spentRecord[token.token] || 0) + 1;
result.push(token.token);
}
return result;
}