Merge branch 'master' into feature/curry
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 · parents 821cc3d, e3eacea · Browse files · 10 files·+69 added−70 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+69 added−70 removed
- tests:+34 added−34 removed
- other:+35 added−36 removed
Provenance
- Commit
946a2b9- Tree
4db0c25- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent 1
821cc3d- Parent 2
e3eacea
10 files changed+69 added−70 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 runTests("es5", immerEs5)8 9 function runTests(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 linesmodified:images/performance.pngbinary
A binary file, modified.
added:images/proxy.pngbinary
A binary file, added.
added:images/tree.pngbinary
A binary file, added.
modified:changelog.md+5 added
1 # Changelog2+3+### 0.3.14+5+* Republished, somehow NPM still returned 0.2.26+7 ### 0.3.0 (8-1-2018)8 9 * Increased performance of the proxy-based implementation by a factor 2x - 3x. [#38](https://github.com/mweststrate/immer/pull/38)10 * Improved typescript typings [#40](https://github.com/mweststrate/immer/pull/40) by [Julien Cavaleiro](https://github.com/Julienng)34 unmodified linesmodified:package.json+1 added-1 removed
1 {2 "name": "immer",3- "version": "0.3.0",3+ "version": "0.3.1",4 "description": "Create your next immutable state by mutating the current one",5 "main": "immer.js",6 "types": "./index.d.ts",7 "scripts": {49 unmodified linesmodified:readme.md+23 added-29 removed
14 unmodified lines15 Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.16 It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.17 18 The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_.19-Once all your mutations are completed, immer will produce the _nextState_ based on the mutations to the draft state.19+Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state.20 This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.21 22 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).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 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 28-## Installation29-30-`npm install immer`31-28 ## API29 34-The immer package exposes a default function that does all the work.30+The Immer package exposes a default function that does all the work.31 36-`immer(currentState, fn: (draftState) => void): nextState`32+`produce(currentState, producer: (draftState) => void): nextState`33 34 There is also a curried overload that is explained [below](#currying)35 36 ## Example37 38 ```javascript43-import immer from "immer"39+import produce from "immer"40 41 const baseState = [42 {43 todo: "Learn typescript",4 unmodified lines48 done: false49 }50 ]51 56-const nextState = immer(baseState, draftState => {52+const nextState = produce(baseState, draftState => {53 draftState.push({ todo: "Tweet about it" })54 draftState[1].done = true55 })56 ```57 62-The interesting thing about `immer` 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 unmodified24 unmodified lines87 ## Reducer Example88 89 Here is a simple example of the difference that Immer could make in practice.90 95-91 ```javascript92 // Redux reducer93 // Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js94 const byId = (state, action) => {11 unmodified lines106 }107 }108 ```109 115-After using immer, that simply becomes:110+After using Immer, that simply becomes:111 112 ```javascript118-import immer from 'immer'113+import produce from 'immer'114 115 const byId = (state, action) =>116 produce(state, draft => {117 switch (action.type) {6 unmodified lines124 ```125 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 133-_Note, creating Redux reducer is just a sample application of the `immer` package.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 ## Currying17 unmodified lines150 151 This mechanism can also nicely be leveraged to further simplify our example reducer:152 153 ```javascript159-154 const byId = produce((draft, action) => {155 switch (action.type) {156 case RECEIVE_PRODUCTS:157 action.products.forEach(product => {9 unmodified lines167 168 ## Auto freezing169 170 Immer automatically freezes any state trees that are modified using `produce`.177- This protects against accidental modifications of the state tree outside of an immer function.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 182-## Using immer on older JavaScript environments176+## Using Immer on older JavaScript environments177 184-By default `immer` tries to use proxies for optimal performance.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 2 unmodified lines185 ```186 187 ## More reducer examples188 195-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.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 ```javascript193 // Plain reducer6 unmodified lines200 }201 202 // With immer203 function insertItem(array, action) {210- return immer(array, draft => {204+ return produce(array, draft => {205 draft.splice(action.index, 0, action.item)206 })207 }208 6 unmodified lines215 }216 217 // With immer218 function removeItem(array, action) {225- return immer(array, draft => {219+ return produce(array, draft => {220 draft.splice(action.index, 1)221 })222 }223 14 unmodified lines238 }239 240 // With immer241 function updateObjectInArray(array, action) {248- return immer(array, draft => {242+ return produce(array, draft => {243 draft[action.index] = { ...item, ...action.item}244 // Alternatively, since arbitrarily deep updates are supported:245 // Object.assign(draft[action.index], action.item)246 })3 unmodified lines250 ## Pitfalls251 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.260-* 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`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 263-## How does immer work?257+## How does Immer work?258 259 Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/9d73d8f71cb3).260 261 ## Performance262 269-Here is a [simple benchmark](__tests__/performance.js) on the performance of `immer`.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.265 _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.266 267 These tests were executed on Node 8.4.0.2 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).280-* The _reducure_ 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.281-* Immer with proxies is roughly speaking twice as slow as a hand written reducer. This is in practice negclectable.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)283-* The ES5 implentation 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.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 5 unmodified lines