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
Provenance
- Commit
014019e- Tree
4db0c25- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
e3eacea- Parent 2
946a2b9
6 files changed+214 added−108 removed
added:__tests__/curry.js+40 added
12345678910111213141516171819202122232425262728293031323334353637383940"use strict"import * as immerProxy from ".."import * as immerEs5 from "../es5"
runTests("proxy", immerProxy)runTests("es5", immerEs5)
function runTests(name, lib) { describe("curry - " + name, () => { const produce = lib.default
it("should check arguments", () => { expect(() => produce()).toThrow(/produce expects 1 or 2 arguments/) expect(() => produce(() => {}, {})).toThrow( /the first argument to produce should be a plain object or array/ ) expect(() => produce(1, () => {})).toThrow( /the first argument to produce should be a plain object or array/ ) expect(() => produce({}, () => {}, [])).toThrow( /produce expects 1 or 2 arguments/ ) })
it("should support currying", () => { const state = [{}, {}, {}] const mapper = produce((item, index) => { item.index = index })
expect(state.map(mapper)).not.toBe(state) expect(state.map(mapper)).toEqual([ {index: 0}, {index: 1}, {index: 2} ]) expect(state).toEqual([{}, {}, {}]) }) })}modified:__tests__/frozen.js+3 added-3 removed
1234567678991011121344 unmodified lines"use strict"import * as immerProxy from ".."import * as immerEs5 from "../es5"import deepFreeze from "deep-freeze"
runBaseTest("proxy", immerProxy)runBaseTest("es5", immerEs5)runTests("proxy", immerProxy)runTests("es5", immerEs5)
function runBaseTest(name, lib) {function runTests(name, lib) { describe("auto freeze - " + name, () => { const produce = lib.default const baseState = { object: {a: 1},44 unmodified linesmodified:es5.js+24 added-3 removed
10 unmodified lines11 * 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 */18-function produce(baseState, thunk) {18+function 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+ }32+33+ // 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+ }39+40 let finalizing = false41 let finished = false42 const descriptors = {}43 const states = []147 unmodified lines191 192 // 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 linesmodified:immer.js+26 added-6 removed
70 unmodified lines71 }72 }73 74 /**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 */84-function produce(baseState, thunk) {84+function 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+ }98+99+ // 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 = []106 107 class State {108 constructor(parent, base) {56 unmodified lines165 166 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 lines220 221 // 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 linesmodified:index.d.ts+18 added-2 removed
123456789101112131412151617181920212223242526272829303132333435362137/** * Immer takes a state, and runs a function against it. * That function can freely mutate the state, as it will create copies-on-write. * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned * * If only one argument is passed, this is interpreted as the recipe, and will create a curried function that will execute the recipe * any time it is called with a base state * * @param currentState - the state to start with * @param thunk - function that receives a proxy of the current state as first argument and which can be freely modified * @returns The next state: a new state, or the current state if nothing was modified */export default function<S = any>( currentState: S, thunk: (draftState: S) => void, recipe: (draftState: S) => void): S// curried invocationsexport default function<S = any, A = any, B = any, C = any>( recipe: (draftState: S, a: A, b: B, c: C) => void): (currentState: S, a: A, b: B, c: C) => Sexport default function<S = any, A = any, B = any>( recipe: (draftState: S, a: A, b: B) => void): (currentState: S, a: A, b: B) => Sexport default function<S = any, A = any>( recipe: (draftState: S, a: A) => void): (currentState: S) => Sexport default function<S = any>( recipe: (draftState: S, ...extraArgs: any[]) => void): (currentState: S, ...extraArgs: any[]) => S
/** * Automatically freezes any state trees generated by immer. * This protects against accidental modifications of the state tree outside of an immer function. * This comes with a performance impact, so it is recommended to disable this option in production. * It is by default enabled. */export function setAutoFreeze(autoFreeze: boolean): void;export function setAutoFreeze(autoFreeze: boolean): voidmodified:readme.md+103 added-94 removed
3 unmodified lines4 [](https://coveralls.io/github/mweststrate/immer?branch=master)5 [](https://github.com/prettier/prettier)6 [](https://mobx.js.org/donate.html)7 8-8 _Create the next immutable state tree by simply modifying the current tree_9 10 ---11 10 unmodified lines22 23 24 Using 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).25 27-A 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.26+A 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.27 29-## Installation30-31-`npm install immer`32-28 ## API29 35-The Immer package exposes a single function, which typically, but not necessarily is called `produce`:30+The Immer package exposes a default function that does all the work.31 32 `produce(currentState, producer: (draftState) => void): nextState`33 34+There is also a curried overload that is explained [below](#currying)35+36 ## Example37 38 ```javascript39 import produce from "immer"3 unmodified lines43 todo: "Learn typescript",44 done: true45 },46 {50- todo: "Try Immer",47+ todo: "Try immer",48 done: false49 }50 ]51 2 unmodified lines54 draftState[1].done = true55 })56 ```57 61-The interesting thing about `produce` is that, the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.58+The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.59 60 ```javascript61 // the new item is only added to the next state,62 // base state is unmodified9 unmodified lines72 // changed data not (dûh)73 expect(nextState[1]).not.toBe(baseState[1])74 ```75 79-## Using Immer on older JavaScript environments80-81-By default Immer tries to use proxies for optimal performance.82-However, on older JavaScript engines `Proxy` is not available.83-For example, Microsoft Internet Explorer or React Native on Android.84-In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:85-86-```javascript87-import produce from "immer/es5"88-```89-76 ## Benefits77 92-* 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.84 100-## Auto freezing85+Read further to see all these benefits explained.86 102- 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.106-107- Use `setAutoFreeze(true / false)` to turn this feature on or off.108-87 ## Reducer Example88 111-Here is a simple example of the difference that this approach could make in practice.112-The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)89+Here is a simple example of the difference that Immer could make in practice.90 114-_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)_115-91 ```javascript92+// Redux reducer93+// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js117-const todo = (state, action) => {94+const 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- }129-130- 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 }138-139-const 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 ```109 156-When using Immer, that simply [becomes](https://codesandbox.io/s/xl11qpo9mp):110+After using Immer, that simply becomes:111 112 ```javascript113 import produce from 'immer'114 161-const todos = (state = [], action) =>162- // produce produces nextState from draftState and returns it163- produce(state, draftState => {115+const 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 ```125 180-Creating middleware or a reducer wrapper that applies `produce` automatically is left as exercise for the reader :-).126+Note that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.127 182----128+_Note, creating Redux reducer is just a sample application of the Immer package.129+Immer is not just designed to simplify Redux reducers.130+It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing)_131 132+## Currying133+134+`produce` can be called with one or two arguments.135+The 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.136+The producer function get's passed in the draft, and any further arguments that were passed to the curried function.137+138+For example:139+140+```javascript141+// mapper will be of signature (state, index) => state142+const mapper = produce((draft, index) => {143+ draft.index = index144+})145+146+// example usage147+console.dir([{}, {}, {}].map(mapper))148+//[{index: 0}, {index: 1}, {index: 2}])149+```150+151+This mechanism can also nicely be leveraged to further simplify our example reducer:152+153+```javascript154+const 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+```163+164+Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).165+One think to keep in mind; you cannot use this construction to initialize an uninitialized state. E.g. `draft = {}` doesn't do anything useful.166+167+168+## Auto freezing169+170+ 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.175+176+## Using Immer on older JavaScript environments177+178+By default `produce` tries to use proxies for optimal performance.179+However, on older JavaScript engines `Proxy` is not available.180+For example, Microsoft Internet Explorer or React Native on Android.181+In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:182+183+```javascript184+import immer from "immer/es5"185+```186+187+## More reducer examples188+189 Here 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.190 These examples are semantically equivalent and produce the exact same state.191 192 ```javascript34 unmodified lines227 if(index !== action.index) {228 // This isn't the item we care about - keep it as-is229 return item;230 }231+232 // Otherwise, this is the one we want - return an updated value233 return {234 ...item,235 ...action.item4 unmodified lines240 // With immer241 function 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 ```249 244-## Limitations250+## Pitfalls251 246-* 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)248-249-## Pitfalls:250-252+* 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.256 257+## How does Immer work?258+259+Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/9d73d8f71cb3).260+261 ## Performance262 263 Here is a [simple benchmark](__tests__/performance.js) on the performance of Immer.264 This test takes 100.000 todo items, and updates 10.000 of them.5 unmodified lines270 271 272 Some 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.279 280 ## Credits281 282 Special 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.283+284+## Donations285+286+A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)