For the following code challenge, you may use any language you wish. You are also free to use google and stack-overflow, although I ask that you include citaitons for any significant work.
Please record your time.
Write a function merge that takes two objects/hashes as arguments and returns the first object combined with the second object, according to the following rules:
If a key exists in the first object, but not in the second object, the key/value pair should be added ("merged") into the first object.
merge( {a: 1}, {b: 2} )==>{ a: 1, b: 2 }merge( {c: 3}, {d: 4, z: 9} )==>{ c: 3, d: 4, z: 9 }
If the same key exists in both objects, the values associated with the shared key should be combined, according to the following rules:
- If it is numeric, we are interested in the the sum of the two values:
merge( {a: 1}, {a: 1})==>{a: 2}merge( {b: 1, c: 2}, {a: 1, c: 2} )==>{a: 1, b: 1, c: 4}
- If it is a string, we are interested in the combination of string a and string b, with a space separating the two:
merge({ name: "john" }, { name: "doe"})==>{name: "john doe"}
- If it is an array, we are interested in all the elements, across both arrays:
merge( { list: [1,2,3] }, {list: [9]} )==>{ list: [1,2,3,9] }
- Bonus: If it is an object/hash, we should repeat the above process of combining keys/values (down to at least one level).
merge( {a: 1, b: {greeting: "hello"}}, {a: 1, b: { greeting: "world", z: 9 }} )==>{a: 2, b: {greeting: "hello world", z: 9}}
NOTE: It is safe to assume that shared keys will also share data types. For example, if key "a" exists in both objects, and key "a" holds an integer in the first object, we can safely assume that key "a" will also hold an integer in the second object.
Start the timer!