-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
56 lines (46 loc) · 1.65 KB
/
index.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
export type Mask = number | null | undefined;
export type Flags = number | number[];
const add = (mask: Mask, flags: Flags) => {
if (mask === undefined || mask === null) mask = 0;
const flagsArr = Array.isArray(flags) ? flags : [flags];
return flagsArr.reduce((acc, f) => acc | f, mask);
};
const remove = (mask: Mask, flags: Flags) => {
if (mask === undefined || mask === null) return 0;
const flagsArr = Array.isArray(flags) ? flags : [flags];
return flagsArr.reduce((acc, f) => acc & ~f, mask);
};
const fromArray = (flags: Flags) => add(0, flags);
const toArray = (mask: Mask) => {
if (mask === undefined || mask === null) return [];
return mask
.toString(2)
.split("")
.reverse()
.reduce<number[]>((acc, v) => {
acc.push(+v * Math.pow(2, acc.length));
return acc;
}, [])
.filter((v) => v);
};
const equals = (mask: Mask, flags: Flags) => {
if (mask === undefined || mask === null) return false;
const comparable = fromArray(flags);
return mask === comparable;
};
const includes = (mask: Mask, flags: Flags) => {
if (mask === undefined || mask === null) return false;
const comparable = fromArray(flags);
return (mask & comparable) === comparable;
};
const excludes = (mask: Mask, flags: Flags) => {
if (mask === undefined || mask === null) return false;
return !includes(mask, flags);
};
const noneOf = (mask: Mask, flags: Flags) => {
if (mask === undefined || mask === null) return false;
const comparable = fromArray(flags);
if (mask === 0 && comparable === 0) return false;
return (mask & comparable) === 0;
};
export { add, remove, fromArray, toArray, equals, includes, excludes, noneOf };