Last active
March 13, 2023 21:18
-
-
Save renatoargh/61c4aa3fa7345a664109ba11b21ace4a to your computer and use it in GitHub Desktop.
UUID plus timestamp to ULID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
┌──────────────┬────────────────────────────────────────┐ | |
│ (index) │ Values │ | |
├──────────────┼────────────────────────────────────────┤ | |
│ timestamp │ 1678742260622 │ | |
│ uuid │ 'f0df59ea-bfe2-43a8-98d4-8213348daeb6' │ | |
│ ulid │ '01GVEDC2WE8EM9HN422CT8VBNP' │ | |
│ decodedTime │ 1678742260622 │ | |
│ originalUuid │ '0186DCD6-0B8E-43A8-98D4-8213348DAEB6' │ | |
└──────────────┴────────────────────────────────────────┘ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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