1.0.2 • Published 2 years ago

@ianjdarrow/monotonic v1.0.2

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

monotonic

Always-incrementing unique IDs based on timestamps

monotonic is a simple package to generate unique IDs based on timestamps. We use it to differentiate websocket messages generated by a single server that clients could receive duplicatively over multiple subscriptions.

By default, monotonic generates strings like:

1650627455:000000
1650627455:000001
1650627455:000002
1650627456:000000

...et cetera. There's also an constructor option to return results as numbers.

Usage

import { Monotonic } from "@ianjdarrow/monotonic";

const mono = new Monotonic({
  maxEventsPerBase: number, // default 1_000_000
  resolution: "seconds" | "ms", // default "seconds"
  outputFormat: "string" | "number", // default "string"
});
// 1 million distinct IDs generated
for (let i = 0; i < 1e6; i++) {
  mono.get();
}

You can also split the timestamp and nonce back out. This is mostly useful with outputFormat: 'number'.

const mono = new Monotonic({ outputFormat: "number" });
const ts = mono.get();
// later...
const { timestamp, nonce } = mono.split(ts); // something like { 1650627455, 0 }

monotonic will throw an error if you try to generate more than maxEventsPerBase per resolution. By default this is 1,000,000 events per second.

Be aware: with outputFormat: 'number' and resolution: 'ms', maxEventsPerBase can't exceed 1,000 (to avoid exceeding Number.MAX_SAFE_INTEGER).