Last active
September 9, 2019 13:05
-
-
Save ajeet97/0df14fd8339e8fa4ef25e3cb973ff82a to your computer and use it in GitHub Desktop.
Bit array implementation in javascript using Uint8Array
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
class BitArray { | |
/** | |
* BitArray: Every element is 1 bit in size. | |
* | |
* @param {number} size Size of the BitArray | |
* @param {0|1} initialValue Initialize BitArray with `initialValue` (default: `0`) | |
*/ | |
constructor(size, initialValue = 0) { | |
this._size = Math.ceil(size / 8); | |
this._array = new Uint8Array(this._size); // Default initialized with 0 | |
if (initialValue) this._array.fill(255); | |
} | |
/** | |
* @param {number} bitIndex Index of BitArray | |
* @param {0|1} bitValue Value to be set at `bitIndex` (default: `1`) | |
*/ | |
set(bitIndex, bitValue = 1) { | |
// Ignore out of bound index | |
if (bitIndex >= this._size * 8) return; | |
const index = Math.floor(bitIndex / 8); | |
const shift = 7 - bitIndex % 8; | |
if (bitValue) this._array[index] |= 1 << shift; | |
else this._array[index] &= ~(1 << shift); | |
} | |
/** | |
* @param {number} bitIndex Index of BitArray | |
* @returns {0|1} bit value at `bitIndex` | |
*/ | |
get(bitIndex) { | |
// Return 0 for out of bound index | |
if (bitIndex < 0 || bitIndex >= this._size * 8) return 0; | |
const index = Math.floor(bitIndex / 8); | |
const shift = 7 - bitIndex % 8; | |
const val = this._array[index] & 1 << shift; | |
return val >> shift; | |
} | |
clear() { | |
this._array.fill(0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment