Skip to content

Instantly share code, notes, and snippets.

@PranavSK
Created November 10, 2021 17:04
Show Gist options
  • Save PranavSK/6fec71ff1dc3e0140d1c7f740370e343 to your computer and use it in GitHub Desktop.
Save PranavSK/6fec71ff1dc3e0140d1c7f740370e343 to your computer and use it in GitHub Desktop.
/**
* Generates a unique string for use as ID(s).
* @summary 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).
*
* @example
* var privateName = uid();
* var o = { 'public': 'foo' };
* o[privateName] = 'bar';
*
* @returns A string with unique id.
*/
// Generate unique IDs for use as pseudo-private/protected names.
function uid() {
let a = new Uint32Array(3);
window.crypto.getRandomValues(a);
return (performance.now().toString(36) + Array.from(a).map(
A => A.toString(36)).join("")).replace(/\./g, "");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment