Deno nuggets: Create UUID
Published in
1 min readSep 7, 2021
This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.
Problem
How to create a random UUID?
ec20d0b7-a732-4b09-85c8-d1f5e6843726
Solution
Import
No imports are required, as the UUID generation function is part of the core runtime’s crypto module.
Create UUID
To create a V4 compliant UUID, crypto’s randomUUID function can be used.
interface Crypto {
.....
randomUUID(): string;
}
Here are some salient points about this function:
- This is a synchronous function (there is no async variant available)
- A random UUID is produced in every call
- This function doesn’t take any inputs
- The output is a UUID in a string.
Here is an example:
crypto.randomUUID(); //3c0c9501-b77f-49dd-ab75-a4afa92f8972
Here is another example of generating 10 UUIDs:
for(let i=0; i<10; i++)
crypto.randomUUID();//--
1f775e36-1d48-44e0-adfd-71ecaa1dc562
fa9f3768-b4f7-4bab-bf84-4c7953f25e48
3cce30ec-73db-407f-ba2e-859c0f375c0d
5dfa0da4-17b3-4b4f-9ed7-aa9b124cd683
e10e7d0a-22b8-46eb-957f-3106a600cc82
79e4e67d-2a3a-429f-a052-980e4d6022ea
6a261fea-cf74-4378-af97-a650ea5caaed
4119f0fa-8072-4b40-af66-379b487cfb46
1fd299da-d8ba-4dc9-99e4-358637f0d23e
5a438fce-b95e-4126-8e97-24171eab8b68