Skip to content

Commit

Permalink
added jsDoc
Browse files Browse the repository at this point in the history
  • Loading branch information
jimmywarting committed Jun 29, 2021
1 parent 358ba69 commit 9e8b595
Showing 1 changed file with 34 additions and 7 deletions.
41 changes: 34 additions & 7 deletions lib/bitset.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,17 @@
//
//

// A bitset implementation, after that in java.util. Yes there
// already exist such things, but none implement next{Clear|Set}Bit or
// equivalent, and none involved me tooling about for an evening.

'use strict';

/**
* A bitset implementation, after that in java.util. Yes there
* already exist such things, but none implement next{Clear|Set}Bit or
* equivalent, and none involved me tooling about for an evening.
*/
class BitSet {
/**
* @param {number} [size]
*/
constructor(size) {
if (size) {
const numWords = Math.ceil(size / 32);
Expand All @@ -20,14 +24,19 @@ class BitSet {
this.wordsInUse = 0; // = number, not index
}

// Make sure we have at least numWords
/**
* @param {number} numWords
*/
ensureSize(numWords) {
const wordsPresent = this.words.length;
if (wordsPresent < numWords) {
this.words = this.words.concat(new Array(numWords - wordsPresent));
}
}

/**
* @param {number} bitIndex
*/
set(bitIndex) {
const w = wordIndex(bitIndex);
if (w >= this.wordsInUse) {
Expand All @@ -38,22 +47,31 @@ class BitSet {
this.words[w] |= bit;
}

/**
* @param {number} bitIndex
*/
clear(bitIndex) {
const w = wordIndex(bitIndex);
if (w >= this.wordsInUse) return;
const mask = ~(1 << bitIndex);
this.words[w] &= mask;
}

/**
* @param {number} bitIndex
*/
get(bitIndex) {
const w = wordIndex(bitIndex);
if (w >= this.wordsInUse) return false; // >= since index vs size
const bit = 1 << bitIndex;
return !!(this.words[w] & bit);
}

// Give the next bit that's set on or after fromIndex, or -1 if no such
// bit
/**
* Give the next bit that is set on or after fromIndex, or -1 if no such bit
*
* @param {number} fromIndex
*/
nextSetBit(fromIndex) {
let w = wordIndex(fromIndex);
if (w >= this.wordsInUse) return -1;
Expand All @@ -69,6 +87,9 @@ class BitSet {
}
}

/**
* @param {number} fromIndex
*/
nextClearBit(fromIndex) {
let w = wordIndex(fromIndex);
if (w >= this.wordsInUse) return fromIndex;
Expand All @@ -83,10 +104,16 @@ class BitSet {
}
}

/**
* @param {number} bitIndex
*/
function wordIndex(bitIndex) {
return Math.floor(bitIndex / 32);
}

/**
* @param {number} i
*/
function trailingZeros(i) {
// From Hacker's Delight, via JDK. Probably far less effective here,
// since bit ops are not necessarily the quick way to do things in
Expand Down

0 comments on commit 9e8b595

Please sign in to comment.