type-safe, dependency, bit-mask flags with named keys for TypeScript and JavaScript
BitFlags gives you a zero-dependency way to manage sets of boolean flags using bit-masks, but with ergonomic named string keys instead of magic numbers.
- 💯 Type-safe flag keys (TypeScript generics)
- 🚀 Fast bitwise manipulation
- 🔧 Small (single file, tree-shakable)
- 📖 Easy
toNumber,toBinaryString,fromBinaryString,set/clear/toggle/isSet, and more
npm install @boxdox/bitflags
# or
yarn add @boxdox/bitflagsimport{BitFlags}from'@boxdox/bitflags'// Define your flags as string keys mapped to unique bit positions (0-based)constMyFlags={READ: 0,WRITE: 1,EXECUTE: 2,}constflags=newBitFlags(MyFlags)// Set flags by name (type checked!)flags.set('READ').set('EXECUTE')// Check flagsconsole.log(flags.isSet('WRITE'))// falseconsole.log(flags.isSet('EXECUTE'))// true// Convert to numberconstmask=flags.toNumber()// e.g. 0b101 === 5// Binary string representationconsole.log(flags.toBinaryString())// "101" (padded as needed)// Get all set flag namesconsole.log(flags.getCurrentFlags())// ['READ', 'EXECUTE']// Count enabled flagsconsole.log(flags.countOnes())// 2// Clear and set allflags.clearAll()flags.setAll()| Method | Description |
|---|---|
constructor(flags, initialValue?) | create a BitFlags instance |
static fromBinaryString(string, flags) | parse from a binary string |
toNumber() | get the current value as a number |
capacity() | get the minimum bit capacity needed for all flags |
toBinaryString(capacity?) | get a padded binary string |
set(flag) | set a flag (by name or bit), chainable |
clear(flag) | clear a flag (by name or bit), chainable |
toggle(flag) | flip a flag (by name or bit), chainable |
isSet(flag) | checks if given flag is currently set |
clearAll() | clear all flags |
setAll() | set all flags defined |
getCurrentFlags() | array of flag names currently set |
countOnes() | count of flags that are currently enabled |
PR's welcomed for suggesting ideas, fixing bugs, writing tests, improving docs, or submitting code for new features
this is 100% type-safe, with 100% test coverage. please take care of this while raising PR's
fork this repository
install dependencies using Bun:
bun install
check that everything builds and tests pass, along with coverage:
bun run build bun test
MIT