Skip to content

Instantly share code, notes, and snippets.

@crullian
Last active March 11, 2019 20:48
Show Gist options
  • Save crullian/3f55a094b2ac249df92e8c433b3c9ee6 to your computer and use it in GitHub Desktop.
Save crullian/3f55a094b2ac249df92e8c433b3c9ee6 to your computer and use it in GitHub Desktop.
// 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';
const ID = () => {
// 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 `_${Math.random().toString(36).substr(2, 9)}`;
};
// use crypto!
const ID = () => {
const array = new Uint32Array(8);
window.crypto.getRandomValues(array);
let str = '';
for (let i = 0; i < array.length; i++) {
str += (i < 2 || i > 5 ? '' : '-') + array[i].toString(16).slice(-4);
}
return str;
}
// Any length
const ID = (length) => {
if (!length) {
length = 8;
}
let str = '';
for (let i = 1; i < length + 1; i = i + 8) {
str += Math.random().toString(36).substr(2, 10);
}
return ('_' + str).substr(0, length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment