UNPKG

@piyawasin/byte-flags

Version:

A lightweight, type-safe utility library for efficiently storing and managing boolean flags in compact numeric values (8, 16, or 32 bits). Perfect for permission systems, feature flags, status tracking, and any scenario requiring compact boolean storage w

60 lines (59 loc) 2.31 kB
import { BaseFlags } from "./BaseFlags"; import type { FlagsWithFlags } from "./types"; /** * Efficiently stores and manages up to 16 boolean flags in a single short (16-bit value). * * Ideal for permission systems, feature flags, or status tracking where compact * serialization is needed and more than 8 flags are required. * * @example * // Recommended usage with type safety: * const flags = createShortFlags('read', 'write', 'execute', 'admin', 'guest'); * flags.admin = true; // TypeScript knows this is a boolean * * @see {@link createShortFlags} for better TypeScript support */ export declare class ShortFlags extends BaseFlags { private static readonly _MAX_FLAGS; private static readonly _MAX_VALUE; protected readonly MAX_FLAGS = 16; protected readonly MAX_VALUE = 65535; /** * Create a new ShortFlags instance with the specified flag names * @param flagNames Names of flags to initialize (1-16 flags) * @throws Error if more than 16 flags are provided or if flag names are invalid */ constructor(...flagNames: string[]); /** * Create a ShortFlags instance from a JSON string * @param json JSON string or object from toJSON() * @returns New ShortFlags instance * @throws Error if JSON is invalid or flags don't match */ static fromJSON(json: string | object): ShortFlags; /** * Convert the flags to a short value (0-65535) * @returns Short representation of all flags */ toShort(): number; /** * Load flags from a short value * @param s Short value to load (0-65535) * @returns This instance for chaining * @throws Error if the short value is invalid */ fromShort(s: number): this; } /** * Creates a type-safe ShortFlags instance with the specified flag names * @example * // Basic usage * const flags = createShortFlags('read', 'write', 'admin', 'guest'); * flags.admin = true; // TypeScript knows this is a boolean * * // With explicit type * type AppFlags = 'darkMode' | 'notifications' | 'analytics'; * const features = createShortFlags<AppFlags>('darkMode', 'notifications', 'analytics'); * features.darkMode = true; // OK */ export declare function createShortFlags<T extends string>(...flagNames: T[]): FlagsWithFlags<T, ShortFlags>;