snowflakify
Version:
The most complete Snowflake ID generator in TypeScript
62 lines • 2.03 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const process_1 = __importDefault(require("process"));
const FragmentBase_js_1 = __importDefault(require("../FragmentBase.js"));
/**
* ProcessFragment class for process IDs.
* @public
*/
class ProcessFragment extends FragmentBase_js_1.default {
/**
* @param bits - The number of bits for the fragment.
* @param value - A persistent ID value to use for the fragment.
*
* Defaults to the current process ID if omitted.
*
* @throws `[VALUE_INVALID_TYPE]` If value is not a number.
* @throws `[VALUE_INVALID_RANGE]` If value is not within 0 and 2 ** bits - 1
*/
constructor(bits, value) {
super(bits);
if (value) {
if (typeof value !== 'number')
throw new TypeError('[VALUE_INVALID_TYPE]: ProcessFragment value must be a number.');
if (value < 0 || value > this.maxValue)
throw new RangeError('[VALUE_INVALID_RANGE]: ProcessFragment value must be within 0 and 2 ** bits - 1');
this.value = BigInt(value);
}
else {
this.value = this.getProcessId();
}
}
getValue() {
return this.value;
}
destructure(snowflake) {
const bits = BigInt(snowflake) & this.bitMask;
return {
identifier: this.identifier,
value: Number(bits >> this.bitShift),
};
}
updateId() {
this.value = this.getProcessId();
}
/**
* Returns the process ID.
*
* @remarks
* The value is masked by the maxValue to fit in the fragment's bits.
*
* @returns The process ID.
* @internal
*/
getProcessId() {
return BigInt(process_1.default.pid) & this.maxValue;
}
}
exports.default = ProcessFragment;
//# sourceMappingURL=ProcessFragment.js.map