`immer` -> `produce`. Implements #24
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent 2fee7f9 · Browse files · 9 files·+74 added−75 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+74 added−75 removed
- tests:+34 added−34 removed
- other:+40 added−41 removed
Provenance
- Commit
e3eacea- Tree
8bf58c3- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
2fee7f9
9 files changed+74 added−75 removed
modified:__performance_tests__/todo.js+6 added-6 removed
123234567134 unmodified linesExpand all1421431441451461461471481491501511521531541551561561571581591601611621631641651651661671681691701711721731741751751761771781792 unmodified lines"use strict"import immerProxy, {setAutoFreeze as setAutoFreezeProxy} from ".."import immerEs5, {setAutoFreeze as setAutoFreezeEs5} from "../es5"import produceProxy, {setAutoFreeze as setAutoFreezeProxy} from ".."import produceEs5, {setAutoFreeze as setAutoFreezeEs5} from "../es5"import cloneDeep from "lodash.clonedeep"import {List, Record} from "immutable"import deepFreeze from "deep-freeze"
134 unmodified linesExpand all })
measure("immer (proxy) - without autofreeze", () => { setAutoFreezeProxy(false) immerProxy(baseState, draft => { produceProxy(baseState, draft => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } }) setAutoFreezeProxy(true) })
measure("immer (proxy) - with autofreeze", () => { setAutoFreezeProxy(true) immerProxy(frozenBazeState, draft => { produceProxy(frozenBazeState, draft => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } }) })
measure("immer (es5) - without autofreeze", () => { setAutoFreezeEs5(false) immerEs5(baseState, draft => { produceEs5(baseState, draft => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } }) setAutoFreezeEs5(true) })
measure("immer (es5) - with autofreeze", () => { setAutoFreezeEs5(true) immerEs5(frozenBazeState, draft => { produceEs5(frozenBazeState, draft => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } })2 unmodified linesmodified:__tests__/base.js+28 added-28 removed
8 unmodified lines9 runBaseTest("es5 (autofreeze)", immerEs5, true)10 11 function runBaseTest(name, lib, freeze) {12 describe(`base functionality - ${name}`, () => {13- const immer = lib.default13+ const produce = lib.default14 let baseState15 let origBaseState16 17 beforeEach(() => {1 unmodified line19 origBaseState = baseState = createBaseState()20 })21 22 it("should return the original without modifications", () => {23- const nextState = immer(baseState, () => {})23+ const nextState = produce(baseState, () => {})24 expect(nextState).toBe(baseState)25 })26 27 it("should return the original without modifications when reading stuff", () => {28- const nextState = immer(baseState, s => {28+ const nextState = produce(baseState, s => {29 expect(s.aProp).toBe("hi")30 expect(s.anObject.nested).toMatchObject({yummie: true})31 })32 expect(nextState).toBe(baseState)33 })34 35 it("should not return any value: thunk", () => {36 const warning = jest.spyOn(console, "warn")37- immer(baseState, () => ({bad: "don't do this"}))38- immer(baseState, () => [1, 2, 3])39- immer(baseState, () => false)40- immer(baseState, () => "")37+ produce(baseState, () => ({bad: "don't do this"}))38+ produce(baseState, () => [1, 2, 3])39+ produce(baseState, () => false)40+ produce(baseState, () => "")41 42 expect(warning).toHaveBeenCalledTimes(4)43 warning.mockClear()44 })45 46 it("should return a copy when modifying stuff", () => {47- const nextState = immer(baseState, s => {47+ const nextState = produce(baseState, s => {48 s.aProp = "hello world"49 })50 expect(nextState).not.toBe(baseState)51 expect(baseState.aProp).toBe("hi")4 unmodified lines56 57 if (58 ("should preserve type",59 () => {60- const nextState = immer(baseState, s => {60+ const nextState = produce(baseState, s => {61 expect(Array.isArray(s)).toBe(true)62 expect(s.protoType).toBe(Object)63 s.anArray.push(3)64 s.aProp = "hello world"4 unmodified lines69 expect(nextState.protoType).toBe(Object)70 })71 )72 it("deep change bubbles up", () => {73- const nextState = immer(baseState, s => {73+ const nextState = produce(baseState, s => {74 s.anObject.nested.yummie = false75 })76 expect(nextState).not.toBe(baseState)77 expect(nextState.anObject).not.toBe(baseState.anObject)2 unmodified lines80 expect(nextState.anArray).toBe(baseState.anArray)81 })82 83 it("can add props", () => {84- const nextState = immer(baseState, s => {84+ const nextState = produce(baseState, s => {85 s.anObject.cookie = {tasty: true}86 })87 expect(nextState).not.toBe(baseState)88 expect(nextState.anObject).not.toBe(baseState.anObject)1 unmodified line90 expect(nextState.anObject.cookie).toEqual({tasty: true})91 })92 93 it("can delete props", () => {94- const nextState = immer(baseState, s => {94+ const nextState = produce(baseState, s => {95 delete s.anObject.nested96 })97 expect(nextState).not.toBe(baseState)98 expect(nextState.anObject).not.toBe(baseState.anObject)99 expect(nextState.anObject.nested).toBe(undefined)100 })101 102 it("ignores single non-modification", () => {103- const nextState = immer(baseState, s => {103+ const nextState = produce(baseState, s => {104 s.aProp = "hi"105 })106 expect(nextState).toBe(baseState)107 })108 109 it("processes single modification", () => {110- const nextState = immer(baseState, s => {110+ const nextState = produce(baseState, s => {111 s.aProp = "hello"112 s.aProp = "hi"113 })114 expect(nextState).not.toBe(baseState)115 expect(nextState).toEqual(baseState)116 })117 118 it("should support reading arrays", () => {119- const nextState = immer(baseState, s => {119+ const nextState = produce(baseState, s => {120 s.anArray.slice()121 })122 expect(nextState.anArray).toBe(baseState.anArray)123 expect(nextState).toBe(baseState)124 })125 126 it("should support changing arrays", () => {127- const nextState = immer(baseState, s => {127+ const nextState = produce(baseState, s => {128 s.anArray[3] = true129 })130 expect(nextState).not.toBe(baseState)131 expect(nextState.anArray).not.toBe(baseState.anArray)132 expect(nextState.anArray[3]).toEqual(true)133 })134 135 it("should support changing arrays - 2", () => {136- const nextState = immer(baseState, s => {136+ const nextState = produce(baseState, s => {137 s.anArray.splice(1, 1, "a", "b")138 })139 expect(nextState).not.toBe(baseState)140 expect(nextState.anArray).not.toBe(baseState.anArray)7 unmodified lines148 ])149 })150 151 it("can delete array items", () => {152- const nextState = immer(baseState, s => {152+ const nextState = produce(baseState, s => {153 s.anArray.length = 3154 })155 expect(nextState).not.toBe(baseState)156 expect(nextState.anObject).toBe(baseState.anObject)1 unmodified line158 expect(nextState.anArray).toEqual([3, 2, {c: 3}])159 })160 161 it("should support sorting arrays", () => {162- const nextState = immer(baseState, s => {162+ const nextState = produce(baseState, s => {163 s.anArray[2].c = 4164 s.anArray.sort()165 s.anArray[3].c = 5166 })2 unmodified lines169 expect(enumerableOnly(nextState.anArray)).toEqual([1, 2, 3, {c: 5}])170 })171 172 it("should expose property descriptors", () => {173- const nextState = immer([], s => {173+ const nextState = produce([], s => {174 expect(Object.getOwnPropertyDescriptor(s, 0)).toBe(undefined)175 s.unshift("x")176 expect(Object.getOwnPropertyDescriptor(s, 0)).toEqual({177 configurable: true,13 unmodified lines191 })192 })193 194 it("should support sorting arrays - 2", () => {195- const nextState = immer(baseState, s => {195+ const nextState = produce(baseState, s => {196 s.anArray.unshift("x")197 s.anArray[3].c = 4198 s.anArray.sort()199 s.anArray[3].c = 511 unmodified lines211 ])212 })213 214 it("should updating inside arrays", () => {215- const nextState = immer(baseState, s => {215+ const nextState = produce(baseState, s => {216 s.anArray[2].test = true217 })218 expect(nextState).not.toBe(baseState)219 expect(nextState.anArray).not.toBe(baseState.anArray)220 expect(nextState.anArray).toEqual([3, 2, {c: 3, test: true}, 1])221 })222 223 it("reusing object should work", () => {224- const nextState = immer(baseState, s => {224+ const nextState = produce(baseState, s => {225 const obj = s.anObject226 delete s.anObject227 s.messy = obj228 })12 unmodified lines241 expect(nextState.messy.nested).toBe(baseState.anObject.nested)242 })243 244 it("refs should be transparent", () => {245- const nextState = immer(baseState, s => {245+ const nextState = produce(baseState, s => {246 const obj = s.anObject247 s.aProp = "hello"248 delete s.anObject249 obj.coffee = true15 unmodified lines265 expect(nextState.messy.nested).toBe(baseState.anObject.nested)266 })267 268 it("should allow setting to undefined a defined draft property", () => {269- const nextState = immer(baseState, s => {269+ const nextState = produce(baseState, s => {270 s.aProp = undefined271 })272 expect(nextState).not.toBe(baseState)273 expect(baseState.aProp).toBe("hi")3 unmodified lines277 // ES implementation does't protect against all outside modifications, just some..278 if (name === "proxy") {279 it("should revoke the proxy of the baseState after immer function is executed", () => {280 let proxy281- const nextState = immer(baseState, s => {281+ const nextState = produce(baseState, s => {282 proxy = s283 s.aProp = "hello"284 })285 expect(nextState).not.toBe(baseState)14 unmodified lines300 }301 302 it("should revoke the proxy of the baseState after immer function is executed - 2", () => {303 let proxy304- const nextState = immer(baseState, s => {304+ const nextState = produce(baseState, s => {305 proxy = s.anObject306 })307 expect(nextState).toBe(baseState)308 expect(() => {5 unmodified lines314 }).toThrowError(/revoked/)315 })316 317 it("should reflect all changes made in the draft immediately", () => {318- immer(baseState, draft => {318+ produce(baseState, draft => {319 draft.anArray[0] = 5320 draft.anArray.unshift("test")321 // sliced here; jest will also compare non-enumerable keys, which would include the immer Symbols322 expect(draft.anArray.slice()).toMatchObject([41 unmodified linesmodified:__tests__/frozen.js+4 added-4 removed
6 unmodified lines7 runBaseTest("es5", immerEs5)8 9 function runBaseTest(name, lib) {10 describe("auto freeze - " + name, () => {11- const immer = lib.default11+ const produce = lib.default12 const baseState = {13 object: {a: 1},14 array: [1, 2]15 }16 17 it("should freeze objects after modifications", () => {18 expect(Object.isFrozen(baseState.object)).toBe(false) // initially not frozen19- const next = immer(baseState, draft => {19+ const next = produce(baseState, draft => {20 draft.object.c = 221 })22 expect(Object.isFrozen(next.object)).toBe(true)23 expect(Object.isFrozen(next)).toBe(true)5 unmodified lines29 })30 31 it("should freeze arrays after modifications", () => {32 expect(Object.isFrozen(baseState.object)).toBe(false) // initially not frozen33- const next = immer(baseState, draft => {33+ const next = produce(baseState, draft => {34 draft.array.push(3)35 })36 expect(Object.isFrozen(next.object)).toBe(false) // not touched37 expect(Object.isFrozen(next)).toBe(true)8 unmodified lines46 const a = []47 const b = {a: a}48 Object.freeze(a)49 Object.freeze(b)50- const n = immer(b, draft => {50+ const n = produce(b, draft => {51 draft.c = true52 draft.a.push(3)53 })54 expect(n).toEqual({c: true, a: [3]})3 unmodified linesmodified:__tests__/readme.js+2 added-2 removed
1 "use strict"2-import immer from ".."2+import produce from ".."3 4 describe("readme example", () => {5 it("works", () => {6 const baseState = [6 unmodified lines13 done: false14 }15 ]16 17- const nextState = immer(baseState, draft => {17+ const nextState = produce(baseState, draft => {18 draft.push({todo: "Tweet about it"})19 draft[1].done = true20 })21 15 unmodified linesadded:images/proxy.pngbinary
A binary file, added.
added:images/tree.pngbinary
A binary file, added.
modified:es5.js+2 added-2 removed
13 unmodified lines14 * @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 modified16 * @returns {any} a new state, or the base state if nothing was modified17 */18-function immer(baseState, thunk) {18+function produce(baseState, thunk) {19 let finalizing = false20 let finished = false21 const descriptors = {}22 const states = []228 unmodified lines251 autoFreeze = enableAutoFreeze252 }253 254 createHiddenProperty(exports, "__esModule", true)255-module.exports.default = immer255+module.exports.default = produce256 module.exports.setAutoFreeze = setAutoFreezemodified:immer.js+3 added-3 removed
79 unmodified lines80 * @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 modified82 * @returns {any} a new state, or the base state if nothing was modified83 */84-function immer(baseState, thunk) {84+function produce(baseState, thunk) {85 const revocableProxies = []86 87 class State {88 constructor(parent, base) {143 unmodified lines232 if(autoFreeze) {233 Object.freeze(value)234 }235 * */236- autoFreeze && Object.freeze(value);236+ autoFreeze && Object.freeze(value)237 return value238 }239 240 /**10 unmodified lines251 252 Object.defineProperty(exports, "__esModule", {253 value: true254 })255-module.exports.default = immer255+module.exports.default = produce256 module.exports.setAutoFreeze = setAutoFreezemodified:readme.md+29 added-30 removed
15 unmodified lines16 Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.17 It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.18 19 The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_.20-Once all your mutations are completed, immer will produce the _nextState_ based on the mutations to the draft state.20+Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state.21 This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.22 23 24 25-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+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).26 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.28 29 ## Installation1 unmodified line31 `npm install immer`32 33 ## API34 35-The immer package exposes a single function:35+The Immer package exposes a single function, which typically, but not necessarily is called `produce`:36 37-`immer(currentState, fn: (draftState) => void): nextState`37+`produce(currentState, producer: (draftState) => void): nextState`38 39 ## Example40 41 ```javascript42-import immer from "immer"42+import produce from "immer"43 44 const baseState = [45 {46 todo: "Learn typescript",47 done: true48 },49 {50- todo: "Try immer",50+ todo: "Try Immer",51 done: false52 }53 ]54 55-const nextState = immer(baseState, draftState => {55+const nextState = produce(baseState, draftState => {56 draftState.push({ todo: "Tweet about it" })57 draftState[1].done = true58 })59 ```60 61-The interesting thing about `immer` is that, the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.61+The interesting thing about `produce` is that, the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.62 63 ```javascript64 // the new item is only added to the next state,65 // base state is unmodified9 unmodified lines75 // changed data not (dûh)76 expect(nextState[1]).not.toBe(baseState[1])77 ```78 79-## Using immer on older JavaScript environments79+## Using Immer on older JavaScript environments80 81-By default `immer` tries to use proxies for optimal performance.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 immer from "immer/es5"87+import produce from "immer/es5"88 ```89 90 ## Benefits91 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 frozen94+* 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 state99 100 ## Auto freezing101 102- Immer automatically freezes any state trees that are modified using `immer.103- This protects against accidental modifications of the state tree outside of an immer function.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.2 unmodified lines110 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)113 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)_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 116 ```javascript117 const todo = (state, action) => {118 switch (action.type) {33 unmodified lines152 }153 }154 ```155 156-After using immer, that simply [becomes](https://codesandbox.io/s/xl11qpo9mp):156+When using Immer, that simply [becomes](https://codesandbox.io/s/xl11qpo9mp):157 158 ```javascript159-import immer from 'immer'159+import produce from 'immer'160 161 const todos = (state = [], action) =>162- // immer produces nextState from draftState and returns it163- immer(state, draftState => {162+ // produce produces nextState from draftState and returns it163+ produce(state, draftState => {164 switch (action.type) {165 case 'ADD_TODO':166 draftState.push({167 id: action.id,8 unmodified lines176 }177 })178 ```179 180-Creating middleware or a reducer wrapper that applies `immer` automatically is left as exercise for the reader :-).180+Creating middleware or a reducer wrapper that applies `produce` automatically is left as exercise for the reader :-).181 182 ---183 184-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.184+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.185 These examples are semantically equivalent and produce the exact same state.186 187 ```javascript188 // Plain reducer6 unmodified lines195 }196 197 // With immer198 function insertItem(array, action) {199- return immer(array, draft => {199+ return produce(array, draft => {200 draft.splice(action.index, 0, action.item)201 })202 }203 6 unmodified lines210 }211 212 // With immer213 function removeItem(array, action) {214- return immer(array, draft => {214+ return produce(array, draft => {215 draft.splice(action.index, 1)216 })217 }218 3 unmodified lines222 if(index !== action.index) {223 // This isn't the item we care about - keep it as-is224 return item;225 }226-226 // Otherwise, this is the one we want - return an updated value227 return {228 ...item,229 ...action.item2 unmodified lines232 }233 234 // With immer235 function updateObjectInArray(array, action) {237- return immer(array, draft => {236+ return produce(array, draft => {237 draft[action.index] = { ...item, ...action.item}239- // Alternatively, since arbitrarily deep updates are supported:238+ // Or, alternatively:239 // Object.assign(draft[action.index], action.item)240 })241 }242 ```5 unmodified lines248 249 ## Pitfalls:250 251 * 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.253-* 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 `immer`!254-* 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 `immer` block or read from the `currentState` rather than the `draftState`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 * Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.255 256 ## Performance257 259-Here is a [simple benchmark](__tests__/performance.js) on the performance of `immer`.258+Here is a [simple benchmark](__tests__/performance.js) on the performance of Immer.259 This test takes 100.000 todo items, and updates 10.000 of them.260 _Freeze_ indicates that the state tree has been frozen after producing it. This is a _development_ best practice, as it prevents developers from accidentally modifying the state tree.261 262 These tests were executed on Node 8.4.0.5 unmodified lines268 * 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.270 * Immer with proxies is roughly speaking twice as slow as a hand written reducer. This is in practice negligible.271 * 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)273-* 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.272+* 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.273 * 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.274 275 ## Credits276 1 unmodified line