diff --git a/CHANGELOG.md b/CHANGELOG.md index f884f56..1be8827 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## [unreleased] * Add `u._` placeholder for curried functions. +* Fix handling null differently than undefined. `u` and friends will now coerce null to an object if there are updates for it. (https://github.com/substantial/updeep/issues/20) ## [0.6.0] * Remove support for `_.placeholder` in curried methods. This may come back, but it was necessary for the next item. diff --git a/lib/update.js b/lib/update.js index 707b4ec..0421608 100644 --- a/lib/update.js +++ b/lib/update.js @@ -10,7 +10,7 @@ function reduce(object, callback, initialValue) { }, initialValue); } -function resolveUpdates(updates, object = {}) { +function resolveUpdates(updates, object) { return reduce(updates, (acc, value, key) => { let updatedValue = value; @@ -62,17 +62,21 @@ function update(updates, object, ...args) { return updates; } - const resolvedUpdates = resolveUpdates(updates, object); + const defaultedObject = (typeof object === 'undefined' || object === null) ? + {} : + object; + + const resolvedUpdates = resolveUpdates(updates, defaultedObject); if (isEmpty(resolvedUpdates)) { return object; } - if (Array.isArray(object)) { - return updateArray(resolvedUpdates, object); + if (Array.isArray(defaultedObject)) { + return updateArray(resolvedUpdates, defaultedObject); } - return { ...object, ...resolvedUpdates }; + return { ...defaultedObject, ...resolvedUpdates }; } export default wrap(update, 2); diff --git a/test/updeep-spec.js b/test/updeep-spec.js index f05cee9..2c5567c 100644 --- a/test/updeep-spec.js +++ b/test/updeep-spec.js @@ -118,4 +118,15 @@ describe('updeep', () => { expect(result).to.eql({ name: 'Joe Merrill', age: 22 }); }); + + it('defaults to an empty object when null or undefined', () => { + let result = u({ a: { b: 0 } }, { a: null }); + expect(result).to.eql({ a: { b: 0 } }); + + result = u({ a: { b: 0 } }, { a: undefined }); + expect(result).to.eql({ a: { b: 0 } }); + + result = u({ a: { b: 0 } }, { }); + expect(result).to.eql({ a: { b: 0 } }); + }); });