dyn-bitfield

1.0.5 • Public • Published

# Simple Bitfields class

Bitfields are efficient for representing a Set of small positive integers Space requirement: n/8 bytes where n is the highest value

import { BitField } from 'dyn-bitfield'

const field = new BitField // BitField(0) {}

field.set(10) // {10}
field.set(20) // {10, 20}
console.assert(field.has(10) && field.has(20))

field.unset(10) // {20}
console.assert(!field.has(10))

const field2 = new BitField
field2.set(5) // {5}

field.xor(field2) // {5, 20}
console.assert(field.has(5))

field.xor(field2) // {20}
console.assert(!field.has(5))

// Serialize it
const json = JSON.stringify(BitField)
console.log(json) // "[1048576]"
const parsedField = BitField.from(JSON.parse(json))
console.assert(parsedField.has(20))

// Iterator
const field = BitField.of(1, 2, 3, 99)
for(const item of field) console.log(item)
// or
field.iter(item => console.log(item))
// 1
// 2
// 3
// 99

// Find operations
const a = BitField.of(0, 1, 2, 3, /*4,*/ 5, 6)
console.assert(a.firstSet() == 0)
console.assert(a.firstUnset() == 4)
console.assert(a.lastSet() == 6)

console.assert(a.popLast() == 6) // Now 6 is unset
console.assert(a.putFirst() == 4) // Now 4 is set
console.log(a) // BitField(6) { 0, 1, 2, 3, 4, 5 }

Package Sidebar

Install

npm i dyn-bitfield

Weekly Downloads

2

Version

1.0.5

License

GPL-3.0-only

Unpacked Size

5.85 kB

Total Files

3

Last publish

Collaborators

  • blobkat