@toddDec 03.2022 — #To create GUIDs (globally-unique identifiers) in JavaScript, you can use the crypto.getRandomValues() method to generate random values and then format them into a GUID string. Here's an example:
function generateGUID() { // Generate 16 random bytes const bytes = new Uint8Array(16); crypto.getRandomValues(bytes);
// Convert the bytes to a hex string const hex = Array.prototype.map.call(bytes, byte => { return 0${(byte & 0xff).toString(16)}.slice(-2); }).join('');
// Format the hex string as a GUID return ${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}; }
const guid = generateGUID(); console.log(guid); // Example output: 7095db8b-3e76-4c93-9307-9e8ce80f0d5c
In this example, the generateGUID() function uses the crypto.getRandomValues() method to generate 16 random bytes. These bytes are then converted to a hexadecimal string and formatted as a GUID using a series of string manipulations. The resulting GUID string is returned by the function, and can be used as a globally-unique identifier.
Note that this example uses the crypto object, which is part of the Web Cryptography API. This API is not available in all browsers, so you may need to check for its availability and use a polyfill or alternative approach if necessary. Additionally, this example uses the Uint8Array typed array, which may not be available in older browsers. You may need to use a polyfill or alternative approach for typed arrays if necessary.