Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
generate a random ID
function(
a, // the character length of the ID (optional, 32 by default)
b // the radix of the ID (optional, 16 by default)
){
b = b || 16; // use a default radix of 16
return Array( // return an array
a // of the length, if specified,
|| 32 // or 32 otherwise,
)
.join(0) // joined into a string of 0s,
.replace( // and then replace
/./g, // each one, with
function() {
return(
0| // a rounded
Math.random()* // random number between 0 and
b // the radix,
)
.toString(b) // and serialize it into a string.
}
)
}
function(a,b){b=b||16;return Array(a||32).join(0).replace(/0/g,function(){return(0|Math.random()*b).toString(b)})}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Jed Schmidt <http://jed.is>
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 WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "randomID",
"keywords": [ "random", "ID" ]
}
@tsaniel

This comment has been minimized.

Copy link

@tsaniel tsaniel commented Oct 9, 2011

Save 5 bytes.

function(a,b){return(Array(a||32)+'').replace(/,/g,function(){return(0|Math.random(b=b||16)*b).toString(b)})}

@FarSeeing

This comment has been minimized.

Copy link

@FarSeeing FarSeeing commented Mar 1, 2012

And a bit more bytes cut-off:

function(a,b){var c='';a=a||32;while(a--){c+=(0|Math.random(b=b||16)*b).toString(b)}return c}
@tsaniel

This comment has been minimized.

Copy link

@tsaniel tsaniel commented Mar 1, 2012

Shave more bytes off:
function(a,b,c){for(a=a||32;a--;c=[c]+(0|Math.random(b=b||16)*b).toString(b));return c}

@FarSeeing

This comment has been minimized.

Copy link

@FarSeeing FarSeeing commented Mar 2, 2012

Great work!

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