Check out this innovative approach I came up with for creating a typed boolean array using the Proxy
class along with Uint8ClampedArray
as the underlying storage mechanism:
class CustomBooleanArray
{
#storage: Uint8ClampedArray;
[index: number]: boolean;
constructor(length? : number)
{
this.#storage = new Uint8ClampedArray(length ?? 0);
return new Proxy(this, CustomBooleanArray.handler);
}
get length(): number
{
return this.#storage.length;
}
private static handler: ProxyHandler<CustomBooleanArray> =
{
get(target, prop)
{
switch (prop)
{
case 'length':
return target.length;
default:
return target.#storage[Number(prop)] !== 0;
}
},
set(target, index, value): boolean
{
target.#storage[Number(index)] = value ? 1 : 0;
return true;
}
};
}
I put it to the test with:
var example = new CustomBooleanArray(4);
example[1] = true;
example[3] = true;
console.log(example[0]); // Output: false
console.log(example[1]); // Output: true
console.log(example[2]); // Output: false
console.log(example[3]); // Output: true
console.log(example.length); // Output: 4
//console.log(example['str']); // Does not compile
If you have any suggestions for enhancements or fixes, feel free to share.