-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBitFlags.ts
30 lines (25 loc) · 823 Bytes
/
BitFlags.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
export class BitFlags<Options> {
flags: Map<Options, number>;
reverse: boolean;
static toBitFlag(values: boolean[], reverseLogic = false): number {
const bitFlag = values
.map((value) => (reverseLogic ? +!value : +value))
.reverse()
.join('');
return parseInt(bitFlag, 2);
}
constructor(options: Array<Options>, reverse = false) {
this.reverse = reverse;
this.flags = options.reduce((memo, value, i) => {
memo.set(value, 1 << i);
return memo;
}, new Map());
}
has(checkFlag: Options, value: number): boolean {
if (!this.flags.has(checkFlag)) {
throw new Error('Incorrect option provided');
}
const result = (value & (this.flags.get(checkFlag) as number)) === this.flags.get(checkFlag);
return this.reverse ? !result : result;
}
}