Skip to content

Commit

Permalink
-
Browse files Browse the repository at this point in the history
  • Loading branch information
timonson committed Sep 5, 2023
1 parent 1aa8eb3 commit 98439cb
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions util/id.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,36 @@
/**
/**
* generateId.
* generateId
* Produces a random 8-character hexadecimal string.
* @param {number} [length=10]
* @returns {string}
*/
export function generateId() {
return crypto.getRandomValues(new Uint32Array(1))[0].toString(16);
export function generateId(length = 12) {
const minHexChars = 2; // Minimum number of characters required for a valid hex digit
const maxBytes = 65536; // Maximum number of random bytes available
const maxHexChars = maxBytes * 2; // Each byte corresponds to 2 hex characters

if (length < minHexChars) {
// If the length is too small, generate a random number instead
const randomHex = Math.floor(Math.random() * Math.pow(16, minHexChars))
.toString(16).padStart(minHexChars, "0");
return randomHex;
}

if (length > maxHexChars) {
throw new Error(
`Requested length exceeds the maximum allowable (${maxHexChars} characters).`,
);
}

const bytes = new Uint8Array(length / 2);
crypto.getRandomValues(bytes);

const hexString = Array.from(
bytes,
(byte) => byte.toString(16).padStart(2, "0"),
).join("");

return hexString;
}

/**
Expand Down

0 comments on commit 98439cb

Please sign in to comment.