How to wrap around Uint8Array as Boolean array

I tried converting Uint8Array to Boolean Array, but that just did a copy of the array, which means whatever changes in the new Array will not be reflected in the original array.
I tried to create a new subclass around that Uint8Array but, I don’t know to which methods to override so that it can treat the 0s and 1s as false or true.

Hey, @downlotooslow, glad you found the forum! :grin:

This sounds sort of like what might be called an X/Y problem. You’re looking for help with issue X, which is sort of breaking things for you, but the real problem is upstream from that, at issue Y. Read more about it here https://xyproblem.info/

Now, if all you’re actually looking for is to convert a Uint8Array to an array of equivalent Booleans, a helper function can do this:

const toBoolean = (arr) => [...arr].map((el)=>{return Boolean(el);} );

// and, as we're only applying the Boolean to that, we can simplify:
const toBoolean = (arr) => [...arr].map( Boolean );

(Taken from https://replit.com/@TobiasParent/uint8ArrayToBoolean#index.js)
Now note, I am taking the Uint8Array and converting it to a new array using the spread syntax. I found that, if I simply mapped the Uint8Array directly, it kept it as a typed array (of type Uint8). So by mapping it to a new array, it coerces them to their primitive value, which Boolean can operate on.

But it seems that may or may not solve your problem. Because when I do the toBoolean(), it is rendering a snapshot of the Uint8Array, rather than a live copy of the original. If that is what you’re after, I might consider a different approach. For example, if you’re wanting to store the data internally as a Uint8Array, but have it accessible as either a Uint8Array or array of booleans, perhaps a Factory wrapper would be useful. You could then define interface methods to update the original array (setters), and define getters for whatever format you like. But all that would be handled internally to the factory function.

Again, without knowing your application, this is all a thought experiment I’m playing with. We may be looking at the wrong problem.

2 Likes

Thanks for the answer. Here’s what I wanted:

var abc = new SomeClassThatActsLikeUint8Arry(buffer /* arraybuffer */,  buffor_offset,  length);
console.log(abc[0]); // should give true or false instead of 1 or 0)
abc[0] = true;  // should update the internal arraybuffer

I can do like this

but, this will do a copy which is an expensive operation as buffer is too large. So, I’m trying coerce the Uint8Array itself to give true or false instead of 0s or 1s.
I think your Uint8Factory is the right approach for this.

1 Like

Why not just coerce the value into a boolean when you access it?

2 Likes

Sorry, for the late reply. That was the approach I actually took here.

1 Like