Created
April 22, 2012 20:02
-
-
Save Craga89/2466525 to your computer and use it in GitHub Desktop.
Efficient JavaScript Delta-encoding merge method
This file contains 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
var Entity = function(params) { | |
this.merge(Entity.defaults); | |
this.merge(params); | |
}; | |
Entity.defaults = { | |
position: [0, 0], | |
velocity: [0, 0], | |
acceleration: [1, 1] | |
}; | |
Entity.merge = function(obj1, obj2) { | |
var cons = obj1.constructor, | |
func = obj1._mergeFunc, props, p, i; | |
// Create the merge function if one isn't already defined | |
if(!func) { | |
func = ''; | |
// Loop over the first objects default properties and create our merge function | |
if((props = cons.defaults)) { | |
for(p in props) { | |
func += 'if(typeof obj2.'+p+' !== "undefined") {' + | |
'obj.'+p+' = obj2.'+p+';' + | |
'} '; | |
} | |
} | |
// Create and store the new function | |
func = cons._mergeFunc = new Function('obj', 'obj2', func); | |
} | |
// Run the merge function and return the first object | |
return func(obj1, obj2), obj1; | |
}; | |
Entity.prototype.merge = function(obj) { | |
return obj ? Entity.merge(this, obj) : false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sweet! thanks!