I have this helper function in my app that tells me the changes of newData
when compared to oldData
.
How can I refactor my getChanges function to make the test below pass? I thought I may need to make this function recursive since it executes itself from within itself, but I am not totally sure how to implement that.
It looks like this:
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)
}
During my actual tests I use ava's deepEqual to help make the comparison. For whatever reason though, one of the tests that I am running does not pass.
index.ts test 1 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)
})
index.ts test 2 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 } })
})
Basically, I expect nothing to be returned if the test passes, but this test returns this object upon failure:
{
nested: {
- a: 1,
b: 2,
x: 1,
},
}
What am I doing wrong here that is stopping this test from passing?
Cheers!