Created
January 4, 2011 17:21
-
-
Save jed/765059 to your computer and use it in GitHub Desktop.
objective: a function for generating guids of unique entities
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
// objective: a function for generating guids of unique entities | |
// usage: guid( obj ) => integer | |
// approach 1 | |
// entities kept in a hash array, key id found by iteration | |
// pros: | |
// (1) unobtrusive; doesn't pollute objects with expandos | |
// (2) ids can't be accidentally deleted/changed | |
// (3) ids can be assigned to any type of object | |
// (4) id => entity lookup could be implemented for free | |
// cons: | |
// (1) id lookup is O(N), a pretty big deal | |
// (2) GC memory leaked unless "unset" is implemented | |
guid1 = function( guid, objs, i ) { | |
return function( obj ) { | |
for ( i = guid; i--; ) if ( objs[ i ] === obj ) return i | |
return objs[ guid ] = obj, guid++ | |
} | |
}( 1, [] ) | |
// approach 2 | |
// ids kept on each object as a property, a la jQuery | |
// pros: | |
// (1) id lookup is O(1) | |
// (2) no memory leaks, since only primitive integers are stored | |
// cons: | |
// (1) ids can be erased, may interfere with iteration | |
// (2) hacky expando string required | |
guid2 = function( guid, expando ) { | |
return function( obj ) { | |
if ( obj ) { | |
if ( obj[ expando ] ) return obj[ expando ] | |
obj[ expando ] = guid | |
if ( obj[ expando ] ) return guid++ | |
} | |
} | |
}( 1, Date.now().toString( 36 ) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i dunno, is
indexOf
really that much faster?and yeah, my style is a bit, uh, terse i guess...