This project is part of the
@thi.ng/umbrella monorepo.
About
Generator of opaque numeric identifiers with optional support for ID versioning and efficient re-use.
Previously generated IDs that have been discarded are stored in a
memory-efficient implicit list of free IDs and will be re-used. The
overall range of IDs can be specified/limited at construction time and
is based on a given bit width. The largest range currently supported is
32 bits, less if versioning is enabled (configurable).
If versioning is used, the produced IDs are composite values, i.e. the
lowest bits contain the actual ID (e.g for indexing purposes) and other
bits contain the version information.
Both parts can be extracted via the generator's .id()
and .version()
methods. Each time a valid versioned ID is being discarded via
.free(id)
, its version is being increased and, depending on use case
and usage frequency, will eventually overflow back to 0. Once an ID's
version has been updated, the old version is considered invalid. IDs can
be checked for validity via .has(id)
(in constant time).
Status
ALPHA - bleeding edge / work-in-progress
Installation
yarn add @thi.ng/idgen
// ES module
<script type="module" src="https://unpkg.com/@thi.ng/idgen?module" crossorigin></script>
// UMD
<script src="https://unpkg.com/@thi.ng/idgen/lib/index.umd.js" crossorigin></script>
Package sizes (gzipped, pre-treeshake): ESM: 853 bytes / CJS: 909 bytes / UMD: 992 bytes
Dependencies
API
Generated API docs
import { idgen } from "@thi.ng/idgen";
ID generator with 16 bit range and no versioning
const ids = idgen(16, 0);
ids.next();
ids.next();
ids.next(2);
ids.free(0);
ids.has(0);
ids.next()
ids.has(0);
ids.next()
ID generator w/ 24 bit range & 8 bit version range
const ids = idgen(24);
const a = ids.next();
ids.free(a);
const b = ids.next();
ids.id(b);
ids.version(b)
ids.has(b);
ids.has(a);
IDGen is iterable
const ids = ig.idgen(8);
ids.next();
ids.next();
ids.next();
ids.next();
ids.free(2);
[...ids]
ids.next();
[...ids]
Authors
Karsten Schmidt
License
© 2019 - 2020 Karsten Schmidt // Apache Software License 2.0