identifier.ts 838 B

123456789101112131415161718192021222324252627282930
  1. const length = 26
  2. const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  3. let lastTimestamp = 0
  4. let counter = 0
  5. export function ascending() {
  6. return create(false)
  7. }
  8. export function descending() {
  9. return create(true)
  10. }
  11. export function create(descending: boolean, timestamp = Date.now()) {
  12. if (timestamp !== lastTimestamp) {
  13. lastTimestamp = timestamp
  14. counter = 0
  15. }
  16. counter++
  17. const current = BigInt(timestamp) * 0x1000n + BigInt(counter)
  18. const value = descending ? ~current : current
  19. const time = Array.from({ length: 6 }, (_, index) =>
  20. Number((value >> BigInt(40 - 8 * index)) & 0xffn)
  21. .toString(16)
  22. .padStart(2, "0"),
  23. ).join("")
  24. const bytes = crypto.getRandomValues(new Uint8Array(length - 12))
  25. return time + Array.from(bytes, (byte) => chars[byte % 62]).join("")
  26. }