Skip to content

Instantly share code, notes, and snippets.

@subtleGradient
Created September 7, 2008 18:57
Show Gist options
  • Select an option

  • Save subtleGradient/9297 to your computer and use it in GitHub Desktop.

Select an option

Save subtleGradient/9297 to your computer and use it in GitHub Desktop.
function $mergeAdd(){
var mix = {};
var obs = Array.flatten(arguments);
for (var i = 0, l = obs.length; i < l; i++){
var object = obs[i];
if ($type(object) != 'object') continue;
for (var key in object){
var object_prop = object[key], mp = mix[key];
if(mp && $type(object_prop) == 'object' && $type(mp) == 'object')
mix[key] = $mergeAdd(mp, object_prop);
else if(mp && $type(object_prop) == 'number' && $type(mp) == 'number')
mix[key] = mp + $unlink(object_prop);
else if(mp && String(mp).replace(/[^\-\d\.]/g,'').toFloat() && object_prop.replace(/[^\-\d\.]/g,'').toFloat() )
mix[key] = String(mp).replace(/[^\-\d\.]/g,'').toFloat() + object_prop.replace(/[^\-\d\.]/g,'').toFloat();
else
mix[key] = $unlink(object_prop);
}
}
return mix;
};
// ===========
// = TESTING =
// ===========
function pp(object){
switch ($type(object)){
case 'object':
object = $H(object);
var h = '<table>';
object.each(function(value, key){
h += '<tr><th> {key} </th><td> {value} </td></tr>'.substitute({key:key, value: pp(value) })
})
h += '</table>'
return h
break;
case 'array':
object = $A(object);
var h = '';
object.each(function(value, key){
h += '<div> {value} </div>'.substitute({value: pp(value) })
})
return h
break;
case false: return 'false'; break;
case 'string':
case 'number':
case 'boolean':
case 'date':
default: return object.toString();
}
};
var ob1={
a:1
},ob2={
a:2
},ob1_2={
a:3
};
document.write("This")
document.write(pp( $mergeAdd(ob1,ob2) ));
document.write("Should equal")
document.write(pp( ob1_2 ));
ob1={
x:"Fred",
z:"1",
a:1,
b:1,
c:1
},ob2={
x:"Fred",
z:"2",
a:2,
b:2,
c:2
},ob1_2={
x:"Fred",
z:"3",
a:3,
b:3,
c:3
};
document.write("This")
document.write(pp( $mergeAdd(ob1,ob2) ));
document.write("Should equal")
document.write(pp( ob1_2 ));
ob1={
x:"Fred",
z:"$1",
a:1,
b:1,
c:1
},ob2={
x:"Fred",
z:"$2",
a:2,
b:2,
c:2
},ob1_2={
x:"Fred",
z:3,
a:3,
b:3,
c:3
};
document.write("This")
document.write(pp( $mergeAdd(ob1,ob2) ));
document.write("Should equal")
document.write(pp( ob1_2 ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment