https://github.com/john-paul-r/bitflags-ts
An enum-like type for representing & using bit flags
https://github.com/john-paul-r/bitflags-ts
bitfield bitflags npm-package
Last synced: 10 months ago
JSON representation
An enum-like type for representing & using bit flags
- Host: GitHub
- URL: https://github.com/john-paul-r/bitflags-ts
- Owner: John-Paul-R
- License: mit
- Created: 2023-05-26T11:11:55.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2023-05-30T03:19:59.000Z (over 2 years ago)
- Last Synced: 2025-02-28T08:26:36.854Z (11 months ago)
- Topics: bitfield, bitflags, npm-package
- Language: TypeScript
- Homepage: https://bitflags-ts.pages.dev/
- Size: 2.67 MB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: .github/CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
# bitflags-ts
An enum-like type for representing & using bit flags


## Usage
_Note: I don't particularly recommend using this package!_ Bit flags are great,
and can be created and used quite simply in TypeScript (demonstrated in
fantastically concise fashion in [this SO
answer](https://stackoverflow.com/a/39359953/8105643)). This package abstracts
away the bitwise operations, but is not without performance cost. As long as
you're fine with seeing `|` and `&`, use native bit flag enums!
Also note: JS coerces `number`s to 32 bits before performing any bitwise
operations, so the maximum number of flags that can be represented by a bit
flag type is 32!
### `bitFlag`
```ts
const PermissionsFlag = bitFlag('Read', 'Write', 'Execute');
const userPermissions = PermissionsFlag.union(PermissionsFlag.Read, PermissionsFlag.Write);
const canRead = userPermissions.hasFlag(PermissionsFlag.Read); // true
const canExecute = userPermissions.hasFlag(PermissionsFlag.Execute); // false
```
### `createBitFlagsEnum`
An alternative syntax that creates an 'enum' with object-valued (instead of
Number-valued, as in `bitFlag`) members. While this has higher one-time
allocation cost, there are more utilities for working with the values
themselves on the enum member instances.
```ts
const PermissionsFlag = createBitFlagsEnum(['Read', 'Write', 'Execute'] as const);
{ // offers 'or' syntax on the enum value itself
const userPermissions = PermissionsFlag.Read
.or(PermissionsFlag.Write)
.or(PermissionsFlag.Execute);
const canRead = userPermissions.hasFlag(PermissionsFlag.Read); // true
const canExecute = userPermissions.hasFlag(PermissionsFlag.Execute); // true
}
{ // static `union` works in the same fashion as bitFlag
const userPermissions = PermissionsFlag.union([PermissionsFlag.Read, PermissionsFlag.Write]);
const canRead = userPermissions.hasFlag(PermissionsFlag.Read); // true
const canExecute = userPermissions.hasFlag(PermissionsFlag.Execute); // false
}
```