Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Boolean Typed Array in JavaScript?

If I do:

var arr=Uint8Array(1);
arr[0]="hi";
console.log(arr[0]);

The result is 0 instead of "hi". That’s because that type of object (Uint8Array) only admits 8-bit unsigned integers as values for its items.

Is there some type of array-like object made to store only boolean (true/false) values?

How can I create an object of that type?

Note: Please, don’t use watch; it’s not cross-browser. I’m going to use it in any browser.

like image 482
t33st33r Avatar asked May 05 '26 06:05

t33st33r


1 Answers

This isn't exactly what i asked for, but it could be a good implementation:

Uint8Array.prototype.getBitSum=function() {
 var _t=0;
 [].forEach.call(this, function(v, i) { _t+=Math.pow(256,i)*v; });
 return _t;
}

Uint8Array.prototype.getBit=function(b) {
 var _t=this.getBitSum();
 return ((_t & Math.pow(2,b)) != false);
}

Uint8Array.prototype.setBit=function(b, v) {
 var _v=v;
 if (isNaN(_v)) return false;
 var _B=Math.floor(b/8), _B_b=(b%8);
 if (_v) this[_B]|=Math.pow(2,_B_b);
 else this[_B]&=(255-Math.pow(2,_B_b));
 return true;
}

My limited knowledge about some terms made of this a hard work for me. If you find some bug... add comment, please.

The reason of this is to minimize memory reservation. So I think it does right.

like image 77
t33st33r Avatar answered May 08 '26 10:05

t33st33r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!