anyid
Version:
A simple and flexible API to generate various kinds of string ID / code.
76 lines • 2.27 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const assert_1 = __importDefault(require("assert"));
const core_1 = require("./core");
const time_1 = require("./time");
class SequenceValue extends core_1.Value {
constructor() {
super(...arguments);
this.lowerBound = 0;
this.upperBound = 2 ^ 32;
this._resetByTime = false;
this.initialized = false;
}
startWith(n) {
this.lowerBound = n;
}
max(n) {
this.upperBound = n;
}
resetByTime() {
this._resetByTime = true;
}
value() {
if (!this.initialized) {
this.init();
}
if (!this.seq || this.seq > this.upperBound || this.toBeReset()) {
this.seq = this.lowerBound;
}
return this.returnValue(this.seq++);
}
init() {
if (this._resetByTime) {
this.timeValue = this.owner.findValueByType(time_1.TimeValue.name);
assert_1.default(this.timeValue, 'resetByTime() requires time()');
this.time = this.timeValue.value();
}
this.initialized = true;
}
toBeReset() {
if (this._resetByTime) {
const now = this.timeValue.value();
if (this.time.compare(now) !== 0) {
this.time = now;
return true;
}
}
return false;
}
}
class Sequence {
seq() {
this.addValue(new SequenceValue(this));
return this;
}
startWith(n) {
assert_1.default(this.lastValue() instanceof SequenceValue, 'startWith() must follow seq()');
this.lastValue().startWith(n);
return this;
}
max(n) {
assert_1.default(this.lastValue() instanceof SequenceValue, 'max() must follow seq()');
this.lastValue().max(n);
return this;
}
resetByTime() {
assert_1.default(this.lastValue() instanceof SequenceValue, 'resetByTime() must follow seq()');
this.lastValue().resetByTime();
return this;
}
}
exports.Sequence = Sequence;
//# sourceMappingURL=seq.js.map