Here's my take on a implementation of a typed boolean array using the Proxy
class andUint8ClampedArray
as the backing storage for the booleans:
class BooleanArray
{
#actualArray: Uint8ClampedArray;
[index: number]: boolean;
constructor(length? : number)
{
this.#actualArray = new Uint8ClampedArray(length ?? 0);
return new Proxy(this, BooleanArray.indexedHandler);
}
get length(): number
{
return this.#actualArray.length;
}
private static indexedHandler: ProxyHandler<BooleanArray> =
{
get(target, prop)
{
switch (prop)
{
case 'length':
return target.length;
default:
return target.#actualArray[Number(prop)] !== 0;
}
},
set(target, index, value): boolean
{
target.#actualArray[Number(index)] = value ? 1 : 0;
return true;
}
};
}
I tested it with:
var test = new BooleanArray(4);
test[1] = true;
test[3] = true;
console.log(test[0]); // Output: false
console.log(test[1]); // Output: true
console.log(test[2]); // Output: false
console.log(test[3]); // Output: true
console.log(test.length); // Output: 4
//console.log(test['str']); // Doesn't compile
Feel free to suggest improvements/fixes.