Skip to content

Instantly share code, notes, and snippets.

@kenng
Last active August 8, 2016 06:53
Show Gist options
  • Save kenng/3fa1347bd0fe34866f28959fec86d784 to your computer and use it in GitHub Desktop.
Save kenng/3fa1347bd0fe34866f28959fec86d784 to your computer and use it in GitHub Desktop.
ID - a unique ID/name generator for JavaScript
// Generate unique IDs for use as pseudo-private/protected names.
// Similar in concept to
// <http://wiki.ecmascript.org/doku.php?id=strawman:names>.
//
// The goals of this function are twofold:
//
// * Provide a way to generate a string guaranteed to be unique when compared
// to other strings generated by this function.
// * Make the string complex enough that it is highly unlikely to be
// accidentally duplicated by hand (this is key if you're using `ID`
// as a private/protected name on an object).
//
// Use:
//
// var privateName = ID();
// var o = { 'public': 'foo' };
// o[privateName] = 'bar';
var ID = function () {
// Math.random should be unique because of its seeding algorithm.
// Convert it to base 36 (numbers + letters), and grab the first 9 characters
// after the decimal.
return (Date.now().toString(36) + Math.random().toString(36).substr(2, 5)).toUpperCase()
// return '_' + Math.random().toString(36).substr(2, 9);
};
// snippets below extract from http://www.c-sharpcorner.com/blogs/generate-guid-using-javascript1
//http://byronsalau.com/blog/how-to-create-a-guid-uuid-in-javascript/
function createGuid()
{
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
var guid = createGuid();
// http://note19.com/2007/05/27/javascript-guid-generator/
function createGuid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}
var guid = createguid();
// http://guid.us/GUID/JavaScript
function createGuid(){
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0,3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();
}
var guid = createGuid();
// http://slavik.meltser.info/the-efficient-way-to-create-guid-uuid-in-javascript-with-explanation/
function CreateGuid() {
function _p8(s) {
var p = (Math.random().toString(16)+"000000000").substr(2,8);
return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;
}
return _p8() + _p8(true) + _p8(true) + _p8();
}
var guid = createGuid();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment