All files diff.js

100% Statements 15/15
100% Branches 13/13
100% Functions 6/6
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50                            35x 31x                   20x 52x 69x 141x 71x           52x         20x 26x 26x 26x 26x 26x        
import isArray from 'lodash/isArray'
import isEqual from 'lodash/isEqual'
import isNil from 'lodash/isNil'
import isObject from 'lodash/isObject'
import merge from './merge'
import transform from 'lodash/transform'
 
/**
 * replace all values in an object with `null`. used to generate the ORSet for
 * diffing operations.
 *
 * @param {Object} object
 * @return {Object}
 */
const nullify = (object) => transform(object, (result, value, key) => {
  result[key] = (isObject(value) && !isArray(value))
    ? nullify(value)
    : null
})
 
/**
 * @param {object} base
 * @param {object} object
 * @return {object}
 */
const difference = (base, object) => {
  const changes = (object, base) => {
    return transform(object, (result, value, key) => {
      if (!isEqual(value, base[key])) {
        result[key] = (isObject(value) && isObject(base[key]) && !isArray(value))
          ? changes(value, base[key])
          : value
      }
    })
  }
  return (isNil(base))
    ? object
    : changes(object, base)
}
 
const observedRemoveDiff = (base, object) => {
  const diff = difference(base, object)
  const inverseDiff = difference(object, base)
  const nullDiff = nullify(inverseDiff)
  const orDiff = merge({}, nullDiff, diff)
  return orDiff
}
 
export default observedRemoveDiff