43 lines
1.1 KiB
JavaScript
43 lines
1.1 KiB
JavaScript
/**
|
|
* Generates a unique random hash string.
|
|
*
|
|
* Uses `window.crypto` if available, otherwise falls back to Math.random.
|
|
*
|
|
* @param {number} [length=16] - Desired length of the hash
|
|
* @returns {string}
|
|
*
|
|
* @example
|
|
* createUniqueRandomHash(8) // "3f4a1b9c"
|
|
*/
|
|
export function createUniqueRandomHash(length = 16) {
|
|
if (window.crypto && window.crypto.getRandomValues) {
|
|
const array = new Uint8Array(length)
|
|
window.crypto.getRandomValues(array)
|
|
return Array.from(array)
|
|
.map(byte => (byte % 16).toString(16))
|
|
.join('')
|
|
}
|
|
|
|
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
|
|
let hash = ''
|
|
for (let i = 0; i < length; i++) {
|
|
hash += chars.charAt(Math.floor(Math.random() * chars.length))
|
|
}
|
|
return hash
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
* Generates a short unique key string.
|
|
* Uses `Math.random()` and base36 conversion.
|
|
*
|
|
* @returns {string} - A random alphanumeric string (length ~9)
|
|
*
|
|
* @example
|
|
* const key = generateUniqueKey() // e.g., "5gk8q2m1a"
|
|
*/
|
|
export function generateUniqueKey() {
|
|
return Math.random().toString(36).substring(2, 11)
|
|
}
|