Last active
April 4, 2018 02:40
-
-
Save MrHuxu/343fa6b1c35500d8be1c4fc066caefc6 to your computer and use it in GitHub Desktop.
[bit-map] a demo of bit map #snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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