From 98439cb38a165b84f561de17ff76d661d834cc4c Mon Sep 17 00:00:00 2001 From: timonson Date: Tue, 5 Sep 2023 02:19:58 +0200 Subject: [PATCH] - --- util/id.js | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/util/id.js b/util/id.js index affda5c..d2d4961 100644 --- a/util/id.js +++ b/util/id.js @@ -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; } /**