-
-
Save dpatti/178bd9948518256396ff to your computer and use it in GitHub Desktop.
Deep Merge
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
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!") |
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
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