Created
August 2, 2020 14:58
-
-
Save NateTheGreatt/0b852451b23d1567ab6f9369f010546d to your computer and use it in GitHub Desktop.
Infinite Bitmask in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const Bitmask = (length, type=Uint32Array) => { | |
const bitsPerMask = type.BYTES_PER_ELEMENT * 8, | |
totalBytes = Math.ceil(length / bitsPerMask) * type.BYTES_PER_ELEMENT, | |
masks = new type(new SharedArrayBuffer(totalBytes)) | |
const on = (i) => { | |
const masksIndex = Math.floor(i/bitsPerMask) | |
const index = i - bitsPerMask*masksIndex | |
const bitflag = Math.pow(2,index) | |
masks[masksIndex] |= bitflag | |
}, | |
off = (i) => { | |
const masksIndex = Math.floor(i/bitsPerMask) | |
const index = i - bitsPerMask*masksIndex | |
const bitflag = Math.pow(2,index) | |
masks[masksIndex] &= ~bitflag | |
}, | |
set = (i,v) => { | |
if(v) on(i) | |
else off(i) | |
}, | |
get = (i) => { | |
const masksIndex = Math.floor(i/bitsPerMask) | |
const index = i - bitsPerMask*masksIndex | |
const bitflag = Math.pow(2,index) | |
return ((bitflag & masks[masksIndex]) != 0) ? 1 : 0 | |
}, | |
toggle = (i) => { | |
const masksIndex = Math.floor(i/bitsPerMask) | |
const index = i - bitsPerMask*masksIndex | |
const bitflag = Math.pow(2,index) | |
masks[masksIndex] ^= bitflag | |
} | |
return { | |
on, | |
off, | |
set, | |
get, | |
toggle | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment