Skip to content

Commit

Permalink
feat(getRandomUUID): Returns something even without crypto API
Browse files Browse the repository at this point in the history
  • Loading branch information
JF-Cozy committed Oct 2, 2023
1 parent 63b3b1a commit be65396
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions react/helpers/getRandomUUID.js
@@ -1,11 +1,28 @@
/**
* Returns a random UUID
* Returns a random UUID without using window.crypto API
* @returns {string} a random UUID
*/
const createUUID = () => {
const func = c => {
var r = (dt + Math.random() * 16) % 16 | 0
dt = Math.floor(dt / 16)
return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
}

var dt = new Date().getTime()
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, func)

return uuid
}

/**
* Returns a random UUID
* @returns {string} a random UUID
*/
export const getRandomUUID = () => {
if (process.env.NODE_ENV === 'test') {
return 'random-uuid-for-jest'
}

return window?.crypto?.randomUUID?.()
return window?.crypto?.randomUUID?.() || createUUID()
}

0 comments on commit be65396

Please sign in to comment.