Skip to content

Instantly share code, notes, and snippets.

@renatoargh
Last active March 13, 2023 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renatoargh/61c4aa3fa7345a664109ba11b21ace4a to your computer and use it in GitHub Desktop.
Save renatoargh/61c4aa3fa7345a664109ba11b21ace4a to your computer and use it in GitHub Desktop.
UUID plus timestamp to ULID
┌──────────────┬────────────────────────────────────────┐
│ (index) │ Values │
├──────────────┼────────────────────────────────────────┤
│ timestamp │ 1678742260622 │
│ uuid │ 'f0df59ea-bfe2-43a8-98d4-8213348daeb6' │
│ ulid │ '01GVEDC2WE8EM9HN422CT8VBNP' │
│ decodedTime │ 1678742260622 │
│ originalUuid │ '0186DCD6-0B8E-43A8-98D4-8213348DAEB6' │
└──────────────┴────────────────────────────────────────┘
import { Ulid, Uuid4 } from "id128";
import { factory, decodeTime } from 'ulid'
const genUlid = factory();
function convertUuidToUlid(
timestamp: Date,
canonicalUuid: string,
): Ulid {
const uuid = Uuid4.fromCanonical(canonicalUuid);
const convertedUlid = Ulid.fromRaw(uuid.toRaw())
const ulidTimestamp = genUlid(timestamp.valueOf()).slice(0, 10)
const ulidRandom = convertedUlid.toCanonical().slice(10);
return Ulid.fromCanonical(ulidTimestamp + ulidRandom)
}
const timestamp = new Date()
const uuid = 'f0df59ea-bfe2-43a8-98d4-8213348daeb6'
const ulid = convertUuidToUlid(timestamp, uuid)
const originalUuid = Uuid4.fromRaw(ulid.toRaw());
console.table({
timestamp: timestamp.valueOf(),
uuid,
ulid: ulid.toCanonical(),
decodedTime: decodeTime(ulid.toCanonical()),
originalUuid: originalUuid.toCanonical(),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment