diff --git a/CHANGELOG.md b/CHANGELOG.md index 1be8827..8ea8df6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## [unreleased] * Add `u._` placeholder for curried functions. +* Add `u.constant` for replacing an object outright. (https://github.com/substantial/updeep/issues/10) * 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] diff --git a/README.md b/README.md index 6a9d20b..fc9c494 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,35 @@ var result = u({ pet: u.updateIn(['bunny', 'age'], 3) }, { pet: { bunny: { age: expect(result).toEqual({ pet: { bunny: { age: 3 } } }); ``` +### `u.constant(object)` + +Sometimes, you want to replace an object outright rather than merging it. +You'll need to use a function that returns the new object. +`u.constant` creates that function for you. + +```js +var user = { + name: 'Mitch', + favorites: { + band: 'Nirvana', + movie: 'The Matrix' + } +}; + +var newFavorites = { + band: 'Coldplay' +}; + +var result = u({ favorites: u.constant(newFavorites) }, user); + +expect(result).toEqual({ name: 'Mitch', favorites: { band: 'Coldplay' } }); +``` + +```js +var alwaysFour = u.constant(4); +expect(alwaysFour(32)).toEqual(4); +``` + ### `u.if(predicate(, updates)(, object))` Apply `updates` if `predicate` is truthy, or if `predicate` is a function. diff --git a/lib/constant.js b/lib/constant.js new file mode 100644 index 0000000..0a439b2 --- /dev/null +++ b/lib/constant.js @@ -0,0 +1,6 @@ +import freeze from './freeze'; + +export default function constant(object) { + const frozen = freeze(object); + return () => frozen; +} diff --git a/lib/index.js b/lib/index.js index 4c664d8..37ff54b 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,3 +1,4 @@ +import constant from './constant'; import freeze from './freeze'; import is from './is'; import _if from './if'; @@ -13,6 +14,7 @@ import { _ } from './util/curry'; const u = update; u._ = _; +u.constant = constant; u.if = _if; u.ifElse = ifElse; u.is = is; diff --git a/test/constant-spec.js b/test/constant-spec.js new file mode 100644 index 0000000..bcf4593 --- /dev/null +++ b/test/constant-spec.js @@ -0,0 +1,17 @@ +import { expect } from 'chai'; +import u from '../lib'; + +describe('u.constant', () => { + it('returns what it is given... constantly', () => { + const func = u.constant(4); + + expect(func()).to.equal(4); + expect(func('hi')).to.equal(4); + expect(func('hi', 8)).to.equal(4); + expect(func(4)).to.equal(4); + }); + + it('freezes the result', () => { + expect(Object.isFrozen(u.constant({})())).to.be.true; + }); +});