# BooleanArray

**URL:** <https://es.discourse.group/t/booleanarray/841>\
**Category:** 💡 Ideas\
**Created:** [July 2, 2021, 11:40am UTC](https://es.discourse.group/t/booleanarray/841 "2021-07-02T11:40:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mfulton26](https://yyz2.discourse-cdn.com/free1/user_avatar/es.discourse.group/mfulton26/32/578_2.png) [@mfulton26](https://es.discourse.group/u/mfulton26)\
**Post date:** [July 2, 2021, 11:40am UTC](https://es.discourse.group/t/booleanarray/841/1 "2021-07-02T11:40:22Z")

</div>

ECMAScript has a good number of typed arrays now but I do not see one for working with a bits.

There mention of such in [some meeting](https://github.com/tc39/notes/blob/efd0600a27e6da8071a93c6914fe7e0f46ca30c8/meetings/2013-01/jan-30.md) notes years ago but I haven't found more details on why it wasn't implemented (or maybe it was under a different name?):

> MM: A Uint1Array or BooleanArray, where each element is one bit.

I'd like something to use like a [`BitSet`](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/BitSet.html) in Java, etc. for finding first set bits, etc. as well as general purpose array of booleans.

---

<div class="post-metadata">

**Author:** ![claudiameadows](https://yyz2.discourse-cdn.com/free1/user_avatar/es.discourse.group/claudiameadows/32/126_2.png) [@claudiameadows](https://es.discourse.group/u/claudiameadows)\
**Post date:** [July 14, 2021, 7:13am UTC](https://es.discourse.group/t/booleanarray/841/2 "2021-07-14T07:13:21Z")

</div>

For dense resizable boolean arrays (C++ has a STL specialization of `vector<bool>` [that's essentially just that and nothing else](https://www.cplusplus.com/reference/vector/vector-bool/)), you can usually get away with using a bigint and a few simple, relatively standard bit hacks to back such an array. (For fixed arrays, it's slightly more complicated, but only slightly, and in my experience the use cases are always somewhat niche.)

- Read: `(array >> BigInt(offset) & 1n) !== 0n`
- Set: `array | (1n << BigInt(offset))`
- Clear: `array & ~(1n << BigInt(offset))`
- Toggle: `array ^ (1n << BigInt(offset))`
- Update: `array & ~(1n << BigInt(offset)) | (BigInt(Boolean(value)) << BigInt(offset))`
- Push: update bit array + update length
- Pop: extract value + clear bit array + update length
- Shift: `(array & 1n) !== 0n` to extract + `array >> 1n` + update length to update length
- Unshift: `array << 1n | BigInt(Boolean(value))` + update length
- Flip: `~array & ((1n << BigInt(length)) - 1)`
  - Extra mask operation is to keep the main bit array normalized to positive.

And more advanced things also of course have their own relatively straightforward algorithms (though it'd be a great idea to add spec proposals for these), like for counting `true` values or finding the offset of the first `true` value.
