Skip to content

Instantly share code, notes, and snippets.

@LeverOne
Forked from jed/LICENSE.txt
Created October 24, 2011 04:17
Show Gist options
  • Save LeverOne/1308368 to your computer and use it in GitHub Desktop.
Save LeverOne/1308368 to your computer and use it in GitHub Desktop.
generate random v4 UUIDs (107 bytes)

UUID

Returns a random v4 UUID of the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, where each x is replaced with a random hexadecimal digit from 0 to f, and y is replaced with a random hexadecimal digit from 8 to b.

Instance, based on recursion, can be found here.

function(
a,b // placeholders
){
for( // loop :)
b=a=''; // b - result , a - numeric variable
a++<36; //
b+=a*51&52 // if "a" is not 9 or 14 or 19 or 24
? // return a random number or 4
(
a^15 // if "a" is not 15
? // genetate a random number from 0 to 15
8^Math.random()*
(a^20?16:4) // unless "a" is 20, in which case a random number from 8 to 11
:
4 // otherwise 4
).toString(16)
:
'-' // in other cases (if "a" is 9,14,19,24) insert "-"
);
return b
}
function(a,b){for(b=a='';a++<36;b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):'-');return b}
DO WTF YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Alexey Silin <pinkoblomingo@gmail.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WTF YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WTF YOU WANT TO.
{
"name": "UUID",
"description": "Generates random UUIDs",
"contributors": [
"jed",
"subzey",
"tsaniel"
],
"keywords": [
"UUID",
"ID",
"random"
]
}
@stuartpb
Copy link

Okay, I THINK I'm on track to understanding the trick behind the a*51&52 magic now (I suspect it functions similarly to this technique to determine if a number is a power of 2 - note that, due to the bodiless design of this for, where all evaluation is done in the post-loop "increment" statement, this procedure uses one-based indices and never has to deal with the zero case); I'm going to make a tool to see if I can refine the method for discovery.

@LiamKarlMitchell
Copy link

Shout out to arrow functions shaving off 5 characters.

(a,b)=>{for(b=a='';a++<36;b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):'-');return b})

Awesome tricks btw.

@qodesmith
Copy link

@LiamKarlMitchell You have an extra ) at the end of your function. You can save another byte 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment