Last active
February 21, 2024 07:23
-
-
Save weimzh/d972c188a42f66816559c427881639e0 to your computer and use it in GitHub Desktop.
javascript integer set implemented with bitmap
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
// Copyright (c) 2021, Wei Mingzhi <whistler_wmz@users.sf.net>. | |
// SPDX-License-Identifier: BSD-2-Clause | |
const IntSet = function () { | |
this.data = []; | |
this.size = 0; | |
}; | |
IntSet.prototype.add = function (num) { | |
const index = num >> 5; | |
const pos = num & 31; | |
if (this.data[index] === undefined) { | |
this.data[index] = 0; | |
} | |
if (!(this.data[index] & (1 << pos))) { | |
this.data[index] |= 1 << pos; | |
++this.size; | |
} | |
}; | |
IntSet.prototype.delete = function (num) { | |
const index = num >> 5; | |
const pos = num & 31; | |
if (this.data[index] !== undefined && (this.data[index] & (1 << pos))) { | |
this.data[index] &= ~(1 << pos); | |
--this.size; | |
} | |
}; | |
IntSet.prototype.has = function (num) { | |
const index = num >> 5; | |
const pos = num & 31; | |
return !!(this.data[index] && (this.data[index] & (1 << pos))); | |
}; | |
IntSet.prototype.clear = function () { | |
this.data = []; | |
this.size = 0; | |
}; | |
IntSet.prototype.fill = function (size) { | |
this.size = size; | |
this.data = Array((size >> 5) + 1).fill(-1); | |
for (var i = 31; i > (size & 31); --i) { | |
this.data[size >> 5] &= ~(1 << i); | |
} | |
}; | |
IntSet.prototype.forEach = function (cb) { | |
this.data.forEach(function (d, idx) { | |
for (var i = 0; i < 32; ++i) { | |
if (d & (1 << i)) { | |
cb(idx << 5 | i); | |
} | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment