JavaScirpt Bit List
- Bit list is a data structure which may be used to store arrays of boolean values in a number. This method allows such arrays to be used in places where the data shortness is important, e. g. in query string parameters.
- This data structure plays with the binary representation of the numbers. Each element (named "bit") is just a bit of the number. To set the nth bit to true means to add pow(2, n) to the number, to set it to false means to subtract pow(2, n) from the number.
Examples
const BitList = require("js-bit-list");
let list = new BitList();
list.setBit(3, 1);
list.setBit(4, 1);
let num = list.toNumber();
let arr = list.toArray();
let predefinedList = new BitList([0, 0, 0, 1, 1, 0, 0]);
let predefinedListFromNumber = new BitList(31);
Working with objects
Bit list may work with objects so it is convenient to use it when you need to configure something. Imagine you have a list of cities and want to configure, which of them are available for delivery.
const Cities = ["Moscow", "London", "Paris", "Prague"];
const CitiesBitList = BitList.useKeys(Cities);
class CitiesBitList extends BitList {
setObject(object) {
return super.setObject(object, Cities);
}
toObject() {
return super.toObject(Cities);
}
}
let citiesOfRussia = new CitiesBitList().setObject({ Moscow: true });
let citiesNumber = citiesOfRussia.toNumber();
let citiesFromNumber = new CitiesBitList(citiesNumber).toObject();
New in v1.3.0: React support
The new useBitList()
hook may be used in React applications.
import BitList from "js-bit-list";
import { useBitList } from "js-bit-list/hook";
const MyBitList = BitList.useKeys(["myKey"]);
const [list, setList] = useBitList(MyBitList, { myKey: 1 });
const listNumber = list.toNumber();
list.setObject({ myKey: 0 });
setList(list);
New in v2.2.0: .get(), .set(), .keys(), .enabledkeys(), .disabledKeys() and static .checkKey() methods in customized class:
const BitList = require("js-bit-list");
const FruitsBitList = BitList.useKeys(["apple", "banana", "orange"])
FruitsBitList.checkKey("apple")
FruitsBitList.checkKey("tomato")
const fruitsList = new FruitsBitList();
fruitsList.get("apple")
fruitsList.set("orange", 1);
fruitsList.get("orange")
fruitsList.enabledKeys()
fruitsList.disabledKeys()
fruitsList.keys()
See example.js for working example