Add u.constant for replacing an object outright

Fixes #10
This commit is contained in:
Aaron Jensen 2015-08-12 22:19:04 -07:00
parent 5b58b8cfc8
commit 287c4fefad
5 changed files with 55 additions and 0 deletions

View File

@ -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]

View File

@ -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.

6
lib/constant.js Normal file
View File

@ -0,0 +1,6 @@
import freeze from './freeze';
export default function constant(object) {
const frozen = freeze(object);
return () => frozen;
}

View File

@ -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;

17
test/constant-spec.js Normal file
View File

@ -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;
});
});