UNPKG

@thi.ng/idgen

Version:

Generator of opaque numeric identifiers with optional support for ID versioning and efficient re-use

51 lines (50 loc) 1.43 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __decorateClass = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp(target, key, result); return result; }; import { INotifyMixin } from "@thi.ng/api"; import { EVENT_ADDED, EVENT_REMOVED } from "./api.js"; let PrefixedID = class { constructor(prefix, gen) { this.prefix = prefix; this.gen = gen; } next() { const id = this.prefix + this.gen.next(); this.notify({ id: EVENT_ADDED, target: this, value: id }); return id; } free(id) { if (!(id.startsWith(this.prefix) && this.gen.free(Number(id.substring(this.prefix.length))))) return false; this.notify({ id: EVENT_REMOVED, target: this, value: id }); return true; } // @ts-ignore: mixin // prettier-ignore addListener(id, fn, scope) { } // @ts-ignore: mixin // prettier-ignore removeListener(id, fn, scope) { } // @ts-ignore: mixin notify(event) { } }; PrefixedID = __decorateClass([ INotifyMixin ], PrefixedID); const prefixed = (prefix, gen) => new PrefixedID(prefix, gen); export { PrefixedID, prefixed };