Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(getRandomUUID): Returns something even without crypto API
- Loading branch information
Showing
1 changed file
with
19 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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() | ||
} |