Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Forked from anonymous/idOf.js
Last active December 14, 2015 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/5043282 to your computer and use it in GitHub Desktop.
Save gordonbrander/5043282 to your computer and use it in GitHub Desktop.
function uid() {
// Generate a unique and non-colliding id.
return Math.random().toString(36).slice(2);
}
// Create unique, non-colliding ID namespace.
var __id__ = uid();
function idOf(thing) {
return (thing && typeof(thing) === ('object' || 'function')) ?
// If thing is an object or a function, and thing already has an ID,
// return ID. Otherwise assign an ID.
(thing[__id__] = thing[__id__] || uid()) :
// If thing is a primitive, the primitive acts as it's own ID. Return it.
thing;
}
// @TODO use https://github.com/Gozala/Name to properly shim private names.
@gordonbrander
Copy link
Author

In the spirit of http://docs.python.org/2/library/functions.html#id, get a globally unique ID string for any object

Very useful for creating lookup tables.

@Gozala
Copy link

Gozala commented Feb 27, 2013

I'm afraid typeof(null) is "object" so sad JS devs usually do thing && typeof(thing) === "object"

@gordonbrander
Copy link
Author

Sneaky JS. Fixed.

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