const { bitfields } = require('@isluny/bitfields')
const GroupPermissions = bitfields.create(
// Flags
{
'create:post_content': bitfields.bit(0), // (1n << 0n) -> 0n
'read:post_content': bitfields.bit(1), // (1n << 1n) -> 1n
'update:members': bitfields.bit(2), // (1n << 2n) -> 2n
'update:group': bitfields.bit(3), // (1n << 3n) -> 4n
},
// default bits
[
'create:post_content',
'read:post_content'
]
)
import { bitfields } from '@isluny/bitfields'
const GroupPermissions = bitfields.create(
// Flags
{
'create:post_content': bitfields.bit(0), // (1n << 0n) -> 0n
'read:post_content': bitfields.bit(1), // (1n << 1n) -> 1n
'update:members': bitfields.bit(2), // (1n << 2n) -> 2n
'update:group': bitfields.bit(3), // (1n << 3n) -> 4n
},
// default bits
[
'create:post_content',
'read:post_content'
]
)
type GroupPermissions = bitfields.infer<typeof GroupPermissions>
or
class GroupPermissions extends bitfields.Bitfield<typeof GroupPermissions['Flags']> {
static Flags = {
'create:post_content': bitfields.bit(0), // (1n << 0n) -> 0n,
'read:post_content': bitfields.bit(1), // (1n << 1n) -> 1n,
'update:members': bitfields.bit(2), // (1n << 2n) -> 2n,
'update:group': bitfields.bit(3), // (1n << 3n) -> 4n,
}
static defaultBits = GroupPermissions.resolve<typeof GroupPermissions['Flags']>(
'create:post_content',
'read:post_content'
)
}
const permissions = new GroupPermissions()
Checks if a specific bit is set.
permissions.has('create:post_content') // true or false
Adds one or more bits to the bitfield.
permissions.add('update:members')
Removes one or more bits from the bitfield.
permissions.remove('create:post_content')
Returns an object representing the bitfield flags as key-value pairs.
console.log(permissions.serialize())
Returns an array of all enabled flags.
console.log(permissions.toArray())
Returns the numerical representation of the bitfield.
console.log(permissions.toJSON())
You can iterate over a bitfield instance to get all active flags.
for (const flag of permissions) {
console.log(flag)
}
@isluny/bitfields
provides an efficient and flexible way to manage permissions and feature flags using bitfields. Whether you're handling user roles, access permissions, or other flag-based systems, this package offers an intuitive API with TypeScript support. 🚀