Skip to content
Myr

Merge pull request #37 from mweststrate/feature/curry

Before adoption: this commit came in with the history the project adopted, so no landing records it.

support currying

authored by Michel Weststrate · committed by GitHub · parents e3eacea, 946a2b9 · Browse files · 6 files+214 added−108 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+214 added−108 removed

  • tests:+43 added−3 removed
  • other:+171 added−105 removed

6 files+214 added−108 removed

added:__tests__/curry.js+40 added
modified:__tests__/frozen.js+3 added-3 removed
modified:es5.js+24 added-3 removed
10 unmodified lines
11 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned12 *13 * @export14 * @param {any} baseState - the state to start with15 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified15 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified16 * @returns {any} a new state, or the base state if nothing was modified17 */18function produce(baseState, thunk) {18function produce(baseState, producer) {19 // curried invocation20 if (arguments.length === 1) {21 const producer = baseState22 // prettier-ignore23 if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function")24 return function() {25 const args = arguments26 return produce(args[0], draft => {27 args[0] = draft // blegh!28 baseState.apply(null, args)29 })30 }31 }3233 // prettier-ignore34 {35 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)36 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))37 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")38 }3940 let finalizing = false41 let finished = false42 const descriptors = {}43 const states = []
147 unmodified lines
191192 // create proxy for root193 const rootClone = createProxy(undefined, baseState)194 // execute the thunk174 const maybeVoidReturn = thunk(rootClone)195 const maybeVoidReturn = producer(rootClone)196 //values either than undefined will trigger warning;197 !Object.is(maybeVoidReturn, undefined) &&198 console.warn(199 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`
78 unmodified lines
modified:immer.js+26 added-6 removed
70 unmodified lines
71 }72}7374/**75 * Immer takes a state, and runs a function against it.75 * produce takes a state, and runs a function against it.76 * That function can freely mutate the state, as it will create copies-on-write.77 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned78 *79 * @export80 * @param {any} baseState - the state to start with81 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified81 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified82 * @returns {any} a new state, or the base state if nothing was modified83 */84function produce(baseState, thunk) {84function produce(baseState, producer) {85 // curried invocation86 if (arguments.length === 1) {87 const producer = baseState88 // prettier-ignore89 if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function")90 return function() {91 const args = arguments92 return produce(args[0], draft => {93 args[0] = draft // blegh!94 baseState.apply(null, args)95 })96 }97 }9899 // prettier-ignore100 {101 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)102 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))103 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")104 }105 const revocableProxies = []106107 class State {108 constructor(parent, base) {
56 unmodified lines
165166 markChanged() {167 if (!this.modified) {168 this.modified = true149 this.copy = Array.isArray(this.base) // TODO: eliminate those isArray checks?169 this.copy = Array.isArray(this.base)170 ? this.base.slice()151 : Object.assign({}, this.base)171 : Object.assign({}, this.base) // TODO: eliminate those isArray checks?172 Object.assign(this.copy, this.proxies) // yup that works for arrays as well173 if (this.parent) this.parent.markChanged()174 }175 }
44 unmodified lines
220221 // create proxy for root222 const rootClone = createProxy(undefined, baseState)223 // execute the thunk204 const maybeVoidReturn = thunk(rootClone)224 const maybeVoidReturn = producer(rootClone)225 //values either than undefined will trigger warning;226 !Object.is(maybeVoidReturn, undefined) &&227 console.warn(228 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`
48 unmodified lines
modified:index.d.ts+18 added-2 removed
modified:readme.md+103 added-94 removed
3 unmodified lines
4[![Coverage Status](https://coveralls.io/repos/github/mweststrate/immer/badge.svg?branch=master)](https://coveralls.io/github/mweststrate/immer?branch=master)5[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)6[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://mobx.js.org/donate.html)788_Create the next immutable state tree by simply modifying the current tree_910---11
10 unmodified lines
22![immer.png](images/immer.png)2324Using Immer is like having a personal assistant; he takes a letter (the current state), and gives you a copy (draft) to jot changes onto. Once you are done, the assistant will take your draft and produce the real immutable, final letter for you (the next state).2527A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applicable to plain, native JavaScript data structures (arrays and objects) without further needing any library.26A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applied to plain, native JavaScript data structures (arrays and objects) without further needing any library.2729## Installation3031`npm install immer`3228## API2935The Immer package exposes a single function, which typically, but not necessarily is called `produce`:30The Immer package exposes a default function that does all the work.3132`produce(currentState, producer: (draftState) => void): nextState`3334There is also a curried overload that is explained [below](#currying)3536## Example3738```javascript39import produce from "immer"
3 unmodified lines
43 todo: "Learn typescript",44 done: true45 },46 {50 todo: "Try Immer",47 todo: "Try immer",48 done: false49 }50]51
2 unmodified lines
54 draftState[1].done = true55})56```5761The interesting thing about `produce` is that, the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.58The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.5960```javascript61// the new item is only added to the next state,62// base state is unmodified
9 unmodified lines
72// changed data not (dûh)73expect(nextState[1]).not.toBe(baseState[1])74```7579## Using Immer on older JavaScript environments8081By default Immer tries to use proxies for optimal performance.82However, on older JavaScript engines `Proxy` is not available.83For example, Microsoft Internet Explorer or React Native on Android.84In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:8586```javascript87import produce from "immer/es5"88```8976## Benefits7792* Use the language© to construct create your next state93* Use JavaScript native arrays and object94* Automatic immutability; any state tree produced by Immer will by defualt be deeply frozen95* Strongly typed, no string based paths etc96* Deep updates are trivial97* Small, dependency free library with minimal api surface98* No accidental mutations of current state, but intentional mutations of a draft state78* Immutability with normal JavaScript objects and arrays. No new APIs to learn!79* Strongly typed, no string based paths selectors etc.80* Structural sharing out of the box81* Object freezing out of the box82* Deep updates are a breeze83* Boilerplate reduction. Less noise, more concise code.84100## Auto freezing85Read further to see all these benefits explained.86102 Immer automatically freezes any state trees that are modified using `produce`.103 This protects against accidental modifications of the state tree outside of a producer function.104 This comes with a performance impact, so it is recommended to disable this option in production.105 It is by default enabled.106107 Use `setAutoFreeze(true / false)` to turn this feature on or off.10887## Reducer Example88111Here is a simple example of the difference that this approach could make in practice.112The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)89Here is a simple example of the difference that Immer could make in practice.90114_Note, this is just a sample application of the Immer package. Immer is not just designed to simplify Redux reducers. It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing)_11591```javascript92// Redux reducer93// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js117const todo = (state, action) => {94const byId = (state, action) => {95 switch (action.type) {119 case 'ADD_TODO':96 case RECEIVE_PRODUCTS:97 return {121 id: action.id,122 text: action.text,123 completed: false124 }125 case 'TOGGLE_TODO':126 if (state.id !== action.id) {127 return state128 }129130 return {98 ...state,132 completed: !state.completed99 ...action.products.reduce((obj, product) => {100 obj[product.id] = product101 return obj102 }, {})103 }104 default:105 return state106 }107}138139const todos = (state = [], action) => {140 switch (action.type) {141 case 'ADD_TODO':142 return [143 ...state,144 todo(undefined, action)145 ]146 case 'TOGGLE_TODO':147 return state.map(t =>148 todo(t, action)149 )150 default:151 return state152 }153}108```109156When using Immer, that simply [becomes](https://codesandbox.io/s/xl11qpo9mp):110After using Immer, that simply becomes:111112```javascript113import produce from 'immer'114161const todos = (state = [], action) =>162 // produce produces nextState from draftState and returns it163 produce(state, draftState => {115const byId = (state, action) =>116 produce(state, draft => {117 switch (action.type) {165 case 'ADD_TODO':166 draftState.push({167 id: action.id,168 text: action.text,169 completed: false118 case RECEIVE_PRODUCTS:119 action.products.forEach(product => {120 draft[product.id] = product121 })171 return172 case 'TOGGLE_TODO':173 const todo = draftState.find(todo => todo.id === action.id)174 todo.completed = !todo.completed175 return122 }123 })124```125180Creating middleware or a reducer wrapper that applies `produce` automatically is left as exercise for the reader :-).126Note that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.127182---128_Note, creating Redux reducer is just a sample application of the Immer package.129Immer is not just designed to simplify Redux reducers.130It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing)_131132## Currying133134`produce` can be called with one or two arguments.135The one argument version is intended to be used as currying. This means that you get a pre-pound producer, that only needs a state to produce the value from.136The producer function get's passed in the draft, and any further arguments that were passed to the curried function.137138For example:139140```javascript141// mapper will be of signature (state, index) => state142const mapper = produce((draft, index) => {143 draft.index = index144})145146// example usage147console.dir([{}, {}, {}].map(mapper))148//[{index: 0}, {index: 1}, {index: 2}])149```150151This mechanism can also nicely be leveraged to further simplify our example reducer:152153```javascript154const byId = produce((draft, action) => {155 switch (action.type) {156 case RECEIVE_PRODUCTS:157 action.products.forEach(product => {158 draft[product.id] = product159 })160 }161})162```163164Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).165One think to keep in mind; you cannot use this construction to initialize an uninitialized state. E.g. `draft = {}` doesn't do anything useful.166167168## Auto freezing169170 Immer automatically freezes any state trees that are modified using `produce`.171 This protects against accidental modifications of the state tree outside of a producer.172 This comes with a performance impact, so it is recommended to disable this option in production.173 It is by default enabled.174 Use `setAutoFreeze(true / false)` to turn this feature on or off.175176## Using Immer on older JavaScript environments177178By default `produce` tries to use proxies for optimal performance.179However, on older JavaScript engines `Proxy` is not available.180For example, Microsoft Internet Explorer or React Native on Android.181In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:182183```javascript184import immer from "immer/es5"185```186187## More reducer examples188189Here are some typical reducer examples, take from the Redux [Immutable Update Patterns](https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html) page, and their Immer counter part.190These examples are semantically equivalent and produce the exact same state.191192```javascript
34 unmodified lines
227 if(index !== action.index) {228 // This isn't the item we care about - keep it as-is229 return item;230 }231232 // Otherwise, this is the one we want - return an updated value233 return {234 ...item,235 ...action.item
4 unmodified lines
240// With immer241function updateObjectInArray(array, action) {242 return produce(array, draft => {243 draft[action.index] = { ...item, ...action.item}238 // Or, alternatively:244 // Alternatively, since arbitrarily deep updates are supported:245 // Object.assign(draft[action.index], action.item)246 })247}248```249244## Limitations250## Pitfalls251246* Currently, only tree shaped states are supported. Cycles could potentially be supported as well (PR's welcome)247* Currently, only supports plain objects and arrays. Non-plain data structures (like `Map`, `Set`) not (yet). (PR's welcome)248249## Pitfalls:250252* Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.253* Immer only processes native arrays and plain objects (with a prototype of `null` or `Object`). Any other type of value will be treated verbatim! So if you modify a `Map` or `Buffer` or whatever complex object from the draft state, it will be that very same object in both the base state as the next state. In such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.252* Make sure to modify the draft state you get passed in in the callback function, not the original current state that was passed as the first argument to `produce`!253* Since immer uses proxies, reading huge amounts of data from state comes with an overhead. If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer or read from the `currentState` rather than the `draftState`254* Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`255* Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.256257## How does Immer work?258259Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/9d73d8f71cb3).260261## Performance262263Here is a [simple benchmark](__tests__/performance.js) on the performance of Immer.264This test takes 100.000 todo items, and updates 10.000 of them.
5 unmodified lines
270![performance.png](images/performance.png)271272Some observations:273* The _mutate_, and _deepclone, mutate_ benchmarks establish a baseline on how expensive changing the data is, without immutability (or structural sharing in the deep clone case).269* The _reduce_ and _naive reducer_ are implemented in typical Redux style reducers. The "smart" implementation slices the collection first, and then maps and freezes only the relevant todos. The "naive" implementation just maps over and processes the entire collection.274* The _reducer_ and _naive reducer_ are implemented in typical Redux style reducers. The "smart" implementation slices the collection first, and then maps and freezes only the relevant todos. The "naive" implementation just maps over and processes the entire collection.275* Immer with proxies is roughly speaking twice as slow as a hand written reducer. This is in practice negligible.276* Immer is roughly as fast as ImmutableJS. However, the _immutableJS + toJS_ makes clear the cost that often needs to be paid later; converting the immutableJS objects back to plain objects, to be able to pass them to components, over the network etc... (And there is also the upfront cost of converting data received from e.g. the server to immutable JS)277* The ES5 implementation of Immer is significantly slower. For most reducers this won't matter, but reducers that process large amounts of data might benefit from not (or only partially) using an Immer producer. Luckily, Immer is fully opt-in.278* The peeks in the _frozen_ versions of _just mutate_, _deepclone_ and _naive reducer_ come from the fact that they recursively freeze the full state tree, while the other test cases only freeze the modified parts of the tree.279280## Credits281282Special thanks goes to @Mendix, which supports it's employees to experiment completely freely two full days a month, which formed the kick-start for this project.283284## Donations285286A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)