Skip to content

Instantly share code, notes, and snippets.

@reaktivo
Last active February 18, 2020 14:25
Show Gist options
  • Save reaktivo/0761e183f1ad268fe8283de452e6ed68 to your computer and use it in GitHub Desktop.
Save reaktivo/0761e183f1ad268fe8283de452e6ed68 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).
function 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);
};
// Test collisions
function testCollisions(n) {
let i = 0;
const list = [];
while(i++ < n) {
const guid = id();
if (list.includes(guid)) {
throw new Error('Found collision');
}
list.push(guid);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment