Create a gist now

Instantly share code, notes, and snippets.

@MrHuxu /bit-map.js
Last active Apr 4, 2018

Embed
What would you like to do?
[bit-map] a demo of bit map #snippet
const BitMap = function () {
this.data = [];
};
BitMap.prototype.getIdx = num => parseInt(num / 32);
BitMap.prototype.getPos = num => num % 32;
BitMap.prototype.add = function (num) {
const index = this.getIdx(num);
const pos = this.getPos(num);
if (this.data[index] === undefined) this.data[index] = 0;
this.data[index] |= Math.pow(2, pos);
};
BitMap.prototype.exist = function (num) {
const index = this.getIdx(num);
const pos = this.getPos(num);
return !!(this.data[index] && (this.data[index] & Math.pow(2, pos)));
};
const bitMap = new BitMap();
bitMap.add(1);
bitMap.add(5);
bitMap.add(45);
bitMap.add(95);
console.log(bitMap.data);
for (let i = 0; i < 96; i++) console.log(i, bitMap.exist(i));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment