4
\$\begingroup\$

This function merges two dictionaries, using the value from the later dictionary to resolve conflicts.

I have 5 tests that the program passes successfully:

const cases = [
  [[{ a: 'uno', b: 'due' }, { c: 'tre' }], { a: 'uno', b: 'due', c: 'tre' }],
  [[{ a: 'uno', b: 'due' }, { a: 'uno' }], { a: 'uno', b: 'due' }],
  [[{ a: 'uno', b: 'due' }, { a: 'due' }], { a: 'due', b: 'due' }],
  [[{ a: 'uno' }, { c: 'tre' }], { a: 'uno', c: 'tre' }],
  [[{ a: 'uno' }, {}], { a: 'uno' }],
];

How can I improve this code?

const objects = (first, second) => {
 const object = {};
  for (item of Object.keys(first)) {
    object[item] = first[item];
  }
  for (item of Object.keys(second)) {
    object[item] = second[item];
  }
  return object;
};
\$\endgroup\$
2

1 Answer 1

6
\$\begingroup\$

Function name could be improved

The name objects is not very descriptive of what the function does. One reading the code could get confused and think objects was an array of objects. A more descriptive name might be mergeObjects, mergeDictionaries, etc.

Simplifying the function

As was mentioned in a comment Object.assign() could be used to simplify the function. Note that if more complex dictionaries are needed - e.g. if using values other than primitives like nested objects or arrays, this may not work as expected:

For deep cloning, we need to use alternatives, because Object.assign() copies property values. 1

const cases = [
  [[{ a: 'uno', b: 'due' }, { c: 'tre' }], { a: 'uno', b: 'due', c: 'tre' }],
  [[{ a: 'uno', b: 'due' }, { a: 'uno' }], { a: 'uno', b: 'due' }],
  [[{ a: 'uno', b: 'due' }, { a: 'due' }], { a: 'due', b: 'due' }],
  [[{ a: 'uno' }, { c: 'tre' }], { a: 'uno', c: 'tre' }],
  [[{ a: 'uno' }, {}], { a: 'uno' }],
];
const mergeObjects = (first, second) => Object.assign(first, second);

for (const caseEntry of cases) console.log(JSON.stringify(caseEntry[1]) ===  JSON.stringify(mergeObjects(...caseEntry[0])) ? 
'✅' : '❌')

And utilizing the ES-6 feature Spread syntax ... it can be simplified so the call to the assign method is eliminated:

const cases = [
  [[{ a: 'uno', b: 'due' }, { c: 'tre' }], { a: 'uno', b: 'due', c: 'tre' }],
  [[{ a: 'uno', b: 'due' }, { a: 'uno' }], { a: 'uno', b: 'due' }],
  [[{ a: 'uno', b: 'due' }, { a: 'due' }], { a: 'due', b: 'due' }],
  [[{ a: 'uno' }, { c: 'tre' }], { a: 'uno', c: 'tre' }],
  [[{ a: 'uno' }, {}], { a: 'uno' }],
];
const mergeObjects = (first, second) => ({...first, ...second});

for (const caseEntry of cases) console.log(JSON.stringify(caseEntry[1]) ===  JSON.stringify(mergeObjects(...caseEntry[0])) ? 
'✅' : '❌')

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.