Skip to content

Instantly share code, notes, and snippets.

@Craga89
Created April 22, 2012 20:02
Show Gist options
  • Save Craga89/2466525 to your computer and use it in GitHub Desktop.
Save Craga89/2466525 to your computer and use it in GitHub Desktop.
Efficient JavaScript Delta-encoding merge method
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;
}
@istro
Copy link

istro commented Feb 14, 2013

sweet! thanks!

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