I would like to store boolean values into a Javascript Typed Array. Originally I wanted to have a bidimensional array (making a small Game of Life actually) but it is not possible according to this post : javascript multidimensional Typed array (Int8Array) example
I'm filling the array like so :
const cols = 16;
const rows = 16;
const buffer = new ArrayBuffer(cols * rows);
const cells = new Uint8Array(buffer);
for (let i = 0; i < cols * rows; i++) {
cells[i] = Math.random() < 0.5;
}
Which returns:
Nevertheless, I've been doing some test, and I was wondering what is the point of byteOffset
accessor in the ArrayBuffer ? Mozilla shows an example but I don't get the use case :
When I add a byteOffset
of 2 for example : const cells = new Uint8Array(buffer, 2);
the only difference I've noticed is that my Array has lost 2 elements :
Beside all of this, if you have any suggestions on how to store booleans efficiently, I'd be glad to have your advices !
(just came across this, in case this helps folks finding this question) The byteOffset can be useful when creating multiple views on the same byteArray. E.g. you might have one byteArray with a section of 5 Uint32s followed by 5 Uint8s, e.g.:
results in:
setting a single byte in a Uint32Array through the Uint8Array view:
This example is contrived, but illustrates how one could use an array buffer that contains the backing data for several byteArrays of different byteSize without needing to copy the data.
To use an example a little closer to what you are doing, you could set up an array of typed arrays representing rows for your data matrix:
results in:
As you can see, the row arrays point to the same data as the cells array
As for storing booleans, you could use bitwise operators to store and retrieve 8 booleans per byte, but since JS is not very efficient when doing bit operations, it might not be worth the in-memory savings due to the poorer performance and more complex code, but could be worthwhile for data loading and storing depending on the situation.
That said, here is a code snippet illustration of using bitwise operators for storing booleans compactly in a simulated 2D array based on your game example:
results in: