-
-
Notifications
You must be signed in to change notification settings - Fork 272
/
bitfield.js
38 lines (32 loc) 路 932 Bytes
/
bitfield.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
// Takes a bitfield(str) and index(int) and returns a bool
const hasVoted = (bitfield, index) => {
return Boolean(bitfield[Math.floor(index / 8)] & (128 >> (index % 8)));
}
const setVoted = (bitfield, index) => {
const byteIndex = Math.floor(index / 8);
const bitIndex = index % 8;
const newByteValue = bitfield[byteIndex] | (128 >> bitIndex);
return bitfield.slice(0,byteIndex) + newByteValue + bitfield.slice(byteIndex + 1);
}
const getBitfieldLength = (bitCount) => {
return Math.floor((bitCount + 7) / 8);
}
const getEmptyBitfield = (bitCount) => {
return 'x00'.repeat(getBitfieldLength(bitCount));
}
const getVoteCount = (bitfield) => {
let votes = 0;
for(let i=0; i < bitfield.length * 8; i++) {
if(hasVoted(bitfield, i)) {
votes += 1;
}
}
return votes
}
module.exports = {
hasVoted,
setVoted,
getBitfieldLength,
getEmptyBitfield,
getVoteCount
};