-
-
Save gordonbrander/5043282 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
I'm afraid typeof(null)
is "object"
so sad JS devs usually do thing && typeof(thing) === "object"
Sneaky JS. Fixed.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.