I have a function in my application that helps me identify the changes between new data and old data.
I am looking to refactor my getChanges function so that a particular test can pass successfully. I believe making this function recursive might be necessary since it calls itself from within, but I am unsure of how to approach this.
The current implementation is as follows:
getChanges
helper function:
export function getChanges(oldData: Record<string, any>, newData: Record<string, any>): any {
return Object.entries(newData).reduce((changes, [key, newVal]) => {
if (JSON.stringify(oldData[key]) === JSON.stringify(newVal)) return changes
changes[key] = newVal
return changes
}, {} as any)
}
When running tests, I use ava's deepEqual method for comparison purposes. However, one of my tests is not passing as expected.
Test 1 in index.ts passes
import test from 'ava'
import { getChanges } from '../src/comparisonHelpers.js'
test('getChanges - flat', (t) => {
const a = getChanges({}, {})
const b = {}
t.deepEqual(a, b)
t.deepEqual(getChanges({ a: 1 }, { a: 1 }), {})
t.deepEqual(getChanges({ a: 1 }, {}), {})
t.deepEqual(getChanges({}, { a: 1 }), { a: 1 })
const oldData = { a: 1, b: 1, c: 1 }
const newData = { x: 1, a: 1, b: 2 }
const result = getChanges(oldData, newData)
const expect = { x: 1, b: 2 }
t.deepEqual(result, expect)
})
Test 2 in index.ts does not pass
import test from 'ava'
import { getChanges } from '../src/comparisonHelpers.js'
test('getChanges - nested difference', (t) => {
const oldData = { nested: { a: 1, b: 1, c: 1 } }
const newData = { nested: { x: 1, a: 1, b: 2 } }
const res = getChanges(oldData, newData)
t.deepEqual(res, { nested: { x: 1, b: 2 } })
})
In case of failure, the test returns the following unexpected output:
{
nested: {
- a: 1,
b: 2,
x: 1,
},
}
Any guidance on what could be causing this test to fail would be greatly appreciated.
Thank you!