Skip to content

Instantly share code, notes, and snippets.

@dpatti
Last active August 29, 2015 14:07
Show Gist options
  • Save dpatti/178bd9948518256396ff to your computer and use it in GitHub Desktop.
Save dpatti/178bd9948518256396ff to your computer and use it in GitHub Desktop.
Deep Merge
assert = require('assert')
# Deep merge
#
# - Write a function that takes two objects and returns a new object containing
# the keys and values from both objects
# - Neither input should be modified
# - If the key exists in both objects...
# ...merge the values if they are both objects
# ...give the values in the second object (b) precedence otherwise
isObject = (o) ->
o && o.constructor == Object
merge = (a, b) ->
# TODO
# Test input
a =
hello: "who?"
foo:
bar: 1
first: true
b =
hello: "world!"
foo:
baz: 2
second: false
# Test that the merge gives us the expected results
assert.deepEqual merge(a, b),
hello: "world!"
foo:
bar: 1
baz: 2
first: true
second: false
# Test that we have not modified the input
assert.deepEqual a,
hello: "who?"
foo:
bar: 1
first: true
assert.deepEqual b,
hello: "world!"
foo:
baz: 2
second: false
console.log("All tests pass!")
var assert = require('assert');
// Deep merge
//
// - Write a function that takes two objects and returns a new object containing
// the keys and values from both objects
// - Neither input should be modified
// - If the key exists in both objects...
// ...merge the values if they are both objects
// ...give the values in the second object (b) precedence otherwise
var isObject = function(o){
return o && o.constructor === Object;
};
var merge = function(a, b){
// TODO
};
// Test input
var a = {
hello: "who?",
foo: {
bar: 1,
},
first: true,
};
var b = {
hello: "world!",
foo: {
baz: 2,
},
second: false,
};
// Test that the merge gives us the expected results
assert.deepEqual(merge(a, b), {
hello: "world!",
foo: {
bar: 1,
baz: 2,
},
first: true,
second: false,
});
// Test that we have not modified the input
assert.deepEqual(a, {
hello: "who?",
foo: {
bar: 1,
},
first: true,
});
assert.deepEqual(b, {
hello: "world!",
foo: {
baz: 2,
},
second: false,
});
console.log("All tests pass!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment