Skip to content

Commit

Permalink
feat(objectDiff): add object diff util
Browse files Browse the repository at this point in the history
  • Loading branch information
levithomason committed May 9, 2016
1 parent 56d2ddf commit b80ed65
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/utils/utils.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,15 @@
import _ from 'lodash'

/**
* Created by levithomason on 5/6/16.
* This method is naive and inefficient, intended for development / debugging use only.
* Deleted keys are shown as [DELETED].
* @param {{}} source The source object
* @param {{}} target The target object.
* @returns {{}} A new object containing new/modified/deleted keys.
*/
export const objectDiff = (source, target) => _.transform(source, (res, val, key) => {
// deleted keys
if (!_.has(target, key)) res[key] = '[DELETED]'
// new keys / changed values
else if (!_.isEqual(val, target[key])) res[key] = target[key]
}, {})
60 changes: 60 additions & 0 deletions test/specs/utils/utils-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import _ from 'lodash'

import * as utils from '../../../src/utils/utils'

describe('objectDiff', () => {
let a
let b
beforeEach(() => {
[a, b] = _.times(2, n => ({
undef: undefined,
nil: null,
bool: true,
num: 1,
str: 'foo',
obj: { key: 'val', nested: { key: 'val' } },
func: _.noop,
}))
})

const assertDiff = (diff) => utils.objectDiff(a, b).should.deep.equal(diff)

it('picks up undefined values', () => {
b.nil = undefined
assertDiff({ nil: undefined })
})
it('picks up null values', () => {
b.undef = null
assertDiff({ undef: null })
})
it('picks up boolean values', () => {
b.undef = true
assertDiff({ undef: true })

b.undef = false
assertDiff({ undef: false })
})
it('picks up number values', () => {
b.undef = 0
assertDiff({ undef: 0 })

b.undef = 1
assertDiff({ undef: 1 })
})
it('picks up string values', () => {
b.undef = 'string'
assertDiff({ undef: 'string' })
})
it('picks up object values', () => {
b.obj.key = 'new value'
assertDiff({ obj: b.obj })
})
it('picks up nested object values', () => {
b.obj.nested.key = 'new nested value'
assertDiff({ obj: b.obj })
})
it('shows deleted keys', () => {
delete b.undef
assertDiff({ undef: '[DELETED]' })
})
})

0 comments on commit b80ed65

Please sign in to comment.