Skip to content

Instantly share code, notes, and snippets.

@NateTheGreatt
Created August 2, 2020 14:58
Show Gist options
  • Save NateTheGreatt/0b852451b23d1567ab6f9369f010546d to your computer and use it in GitHub Desktop.
Save NateTheGreatt/0b852451b23d1567ab6f9369f010546d to your computer and use it in GitHub Desktop.
Infinite Bitmask in Javascript
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