(prefix: string, direction: "descending" | "ascending", timestamp?: number)
| 49 | } |
| 50 | |
| 51 | export function create(prefix: string, direction: "descending" | "ascending", timestamp?: number): string { |
| 52 | const currentTimestamp = timestamp ?? Date.now() |
| 53 | |
| 54 | if (currentTimestamp !== lastTimestamp) { |
| 55 | lastTimestamp = currentTimestamp |
| 56 | counter = 0 |
| 57 | } |
| 58 | counter++ |
| 59 | |
| 60 | let now = BigInt(currentTimestamp) * BigInt(0x1000) + BigInt(counter) |
| 61 | |
| 62 | now = direction === "descending" ? ~now : now |
| 63 | |
| 64 | const timeBytes = Buffer.alloc(6) |
| 65 | for (let i = 0; i < 6; i++) { |
| 66 | timeBytes[i] = Number((now >> BigInt(40 - 8 * i)) & BigInt(0xff)) |
| 67 | } |
| 68 | |
| 69 | return prefix + "_" + timeBytes.toString("hex") + randomBase62(LENGTH - 12) |
| 70 | } |
| 71 | |
| 72 | /** Extract timestamp from an ascending ID. Does not work with descending IDs. */ |
| 73 | export function timestamp(id: string): number { |
no test coverage detected