Skip to content

Instantly share code, notes, and snippets.

@riffrain
Last active August 28, 2023 16:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riffrain/3fe0532eff60d43328ad0b46e11d311d to your computer and use it in GitHub Desktop.
Save riffrain/3fe0532eff60d43328ad0b46e11d311d to your computer and use it in GitHub Desktop.
Simple UUID(v4) Generator
function uuidv4_1() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.split('')
.map((c) => {
if (c === 'x') return Math.floor(Math.random() * 0xf).toString(16); // [0-9a-f]
if (c === 'y') return Math.floor(Math.random() * 4 + 8).toString(16); // [89ab]
return c;
})
.join('');
}
function uuidv4_2() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.replace(/x/g, () => Math.floor(Math.random() * 0xf).toString(16))
.replace('y', Math.floor(Math.random() * 4 + 8).toString(16));
}
// faster
function uuidv4_3() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.split('')
.reduce((c, i) => c + (
i === 'x' ? Math.floor(Math.random() * 0xf).toString(16)
: i === 'y' ? Math.floor(Math.random() * 4 + 8).toString(16)
: i), '')
}
function uuidv4_4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.replace(/(x)|(y)|([-4])/g, function(match, p1, p2, p3) {
if (p1) return Math.floor(Math.random() * 0xf).toString(16);
if (p2) return Math.floor(Math.random() * 4 + 8).toString(16);
return p3;
});
}
// oneliner(uuidv4_1)
[...'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'].map((c)=>c==='x'?Math.floor(Math.random()*0xf).toString(16):c==='y'?Math.floor(Math.random()*4+8).toString(16):c).join('');
// oneliner(uuidv4_2)
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/x/g,()=>Math.floor(Math.random() * 0xf).toString(16)).replace('y',Math.floor(Math.random()*4+8).toString(16));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment