@thi.ng/idgen
Version:
Generator of opaque numeric identifiers with optional support for ID versioning and efficient re-use
55 lines (54 loc) • 1.52 kB
JavaScript
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 { assert } from "@thi.ng/errors/assert";
import { EVENT_ADDED, EVENT_REMOVED } from "./api.js";
let MonotonicID = class {
constructor(start = 0, step = 1) {
this.start = start;
this.step = step;
assert(step > 0, "invalid step size");
this.nextID = start;
}
nextID;
next() {
const id = this.nextID;
this.nextID += this.step;
this.notify({ id: EVENT_ADDED, target: this, value: id });
return id;
}
free(id) {
if (!(id >= this.start && id < this.nextID)) 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) {
}
};
MonotonicID = __decorateClass([
INotifyMixin
], MonotonicID);
const monotonic = (start, step) => new MonotonicID(start, step);
export {
MonotonicID,
monotonic
};