led-matrix-ts
Version:
Highly customizable led matrix for the browser
66 lines • 2.1 kB
JavaScript
export class BitArray {
constructor(values) {
this._bitPerIndex = 8;
this._size = values.length;
this._array = new Uint8Array(Math.ceil(this._size / this._bitPerIndex));
this._pointer = 0;
this.pushAll(values);
}
get size() {
return this._size;
}
push(value) {
if (this._pointer == this._size) {
throw `Bit array max size reached (${this._size})`;
}
const mask = this._createMask(this._pointer);
if (this._matchesMask(mask, this._array[this._arrayIndex(this._pointer)])) {
if (value === 0) {
this._array[this._arrayIndex(this._pointer)] ^= mask;
}
}
else {
if (value === 1) {
this._array[this._arrayIndex(this._pointer)] ^= mask;
}
}
this._pointer++;
}
pushAll(values) {
values.forEach((value) => {
this.push(value);
});
}
atIndex(index) {
if (index > this._size) {
throw `Index (${index}) exceeds the size of the bit array (${this._size})`;
}
const mask = this._createMask(index);
return this._matchesMask(mask, this._array[this._arrayIndex(index)]) ? 1 : 0;
}
atIndexRange(index, count) {
if (index + count - 1 > this._size) {
throw `Index (${index}) exceeds the size of the bit array (${this._size})`;
}
const values = [];
for (let i = 0; i < count; i++) {
const mask = this._createMask(index + i);
values.push(this._matchesMask(mask, this._array[this._arrayIndex(index + i)]) ? 1 : 0);
}
return values;
}
_matchesMask(mask, value) {
return (mask & value) != 0;
}
_createMask(index) {
return 1 << (this._bitPerIndex - 1) - this._arrayIndexOffset(index);
}
_arrayIndex(index) {
return Math.floor(index / this._bitPerIndex);
}
_arrayIndexOffset(index) {
return index % this._bitPerIndex;
}
}
;
//# sourceMappingURL=bit-array.js.map