forked from screepers/screeps-snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbitSet.js
60 lines (50 loc) · 1016 Bytes
/
bitSet.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* Posted 23 April 2019 by @warinternal
* os.ds.bitset.js
*/
'use strict';
exports.BitSet = class {
/**
* Defaults to 1 unsigned 32 bit int
* @param {*} val
*/
constructor(val = 1) {
this.store = new Uint32Array(val);
this.width = this.store.BYTES_PER_ELEMENT * 8;
}
calcIndex(bit) {
return [~~(bit / this.width), bit % this.width];
}
isset(bit) {
const [b, i] = this.calcIndex(bit);
return !!(this.store[b] & (1 << i));
}
set(bit) {
const [b, i] = this.calcIndex(bit);
if (b >= this.store.length)
this.resize(b + 1);
this.store[b] |= (1 << i);
return this;
}
unset(bit) {
const [b, i] = this.calcIndex(bit);
this.store[b] &= ~(1 << i);
return this;
}
resize(length = 1) {
const old = this.store;
this.store = new Uint32Array(length);
this.store.set(old);
return this;
}
clear() {
this.store = new Uint32Array(0);
return this;
}
static from(val) {
return new this(val);
}
toString() {
return `[BitSet ${this.store.length}]`;
}
};