Last active
May 23, 2024 18:51
-
-
Save vadimpiven/45f8279d84f47b9857df845126694c39 to your computer and use it in GitHub Desktop.
View for Uint8Array emulating BooleanArray or BitSet
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
// SPDX-License-Identifier: CC0-1.0 | |
// Creative Commons Zero v1.0 Universal License: https://creativecommons.org/publicdomain/zero/1.0/deed | |
class BooleanArrayView { | |
array: Uint8Array; | |
constructor(array: Uint8Array) { | |
this.array = array; | |
return new Proxy(this, { | |
get(target, prop) { | |
return prop in target | |
? target[prop as keyof typeof target] | |
: target.get(Number(prop)); | |
} | |
}); | |
} | |
get(index: number) { | |
const chunkIndex = Math.floor(index / 8); | |
const mask = 1 << (7 - (index % 8)); | |
return (this.array[chunkIndex] & mask) > 0; | |
} | |
} | |
const data = new Uint8Array([128]); // 0b1000'0000 | |
const view2 = new BooleanArrayView(data); | |
console.log(view2[0]); // true | |
console.log(view2.get(1)); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment