Created
February 26, 2013 23:17
-
-
Save anonymous/5043277 to your computer and use it in GitHub Desktop.
idOf - in the spirit of <http://docs.python.org/2/library/functions.html#id>, get a globally unique ID string for any object
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) { | |
var type = typeof(thing); | |
return (type === 'object' || type === '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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment