This is not the first BitSet implementation for JavaScript. I doubt it will be the last. I set out not wanting to take on another external dependency, so to speak, and have found it interesting, if a bit tricky to come up with a working functional BitSet for JavaScript.
My design goals starting out are to provide an analog for concepts such as:
- .NET Framework System.Collections.BitArray
- C++ std::bitset
- boost::dynamic_bitset
I also wanted for a BitSet to exhibit immutable characteristics, especially when operations among two or more instances were concerned. These should return a new instance with the expected result based on the two or more operands.
I may accomplish feature parity, but for the moment this is a good start, and will continue to work on it until I am satisfied. Contributors are always welcome as well if you find it useful.
I believe I accomplished immutability but with a couple of interesting language runtime limitations. Specifically having to do with the fact that in JavaScript everything is held as a reference. I mean, everything.
- So for things like default values, I must use factory methods and return the interesting details.
- Also, any data or lengths and such contributing to new instances must be serialized and deserialized via JSON.stringify followed by JSON.parse. Not the most graceful solution, but probably the best we can do.
- I also avoided using Int32Array, per se, in favor of JSON arrays. These are simple enough and are easy to construct and work with.
- I encountered an issue at sign bit boundaries which yielded negative numbers that should not be there. To avoid this I dialed back the size for each element from 32 to 16. This works, but with the trade off of doubling the size of the internally maintained
data
array. I may be able to get away with extending that range a bit by pushing the boundary to the next byte, or 24 bits, instead of 16, but have not explored that much yet, and I want to avoid the math for odd numbered boundaries.
Feel free to have a look at the test cases for examples on how to work with the BitSet.
I have not tested for performance yet, but I imagine the reference limitations are a big one that will make things interesting.