Merge branch 'kachkaev-add-failing-tests-for-recursive-use'
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 41bb8b9, 1460ec1 · Browse files · 6 files·+331 added−148 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+331 added−148 removed
- tests:+203 added−11 removed
- other:+128 added−137 removed
Provenance
- Commit
3db727b- Tree
48a8b93- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent 1
41bb8b9- Parent 2
1460ec1
6 files changed+331 added−148 removed
modified:__tests__/flow/flow.js.flow+16 added-11 removed
13 unmodified lines14 15 console.log(result.x)16 17 const result2 = produce({x: 3}, draft => {18- return {x: 4};18+ return {x: 4}19 })20 21 console.log(result2.x)22 23-const f = produce((draft): ({x: number}) => { return {x: 4}; });24-f({x: 3});23+const f = produce((draft): {x: number} => {24+ return {x: 4}25+})26+f({x: 3})27 28 const f2 = produce((draft): void => {})29 f2({x: 3})30 13 unmodified lines44 produce({x: 3}, [])45 46 {47 // curried & initial arg48+ const f = produce(46- const f = produce((state, increment: number): void => {47- state.x += increment48- }, { x: 3})49+ (state, increment: number): void => {50+ state.x += increment51+ },52+ {x: 3}53+ )54 55 // $ExpectError Too few arguments51- f({x : 5})56+ f({x: 5})57 58 // $ExpectError54- f({x : 5}, "test")59+ f({x: 5}, "test")60 56- f({x : 5}, 3)61+ f({x: 5}, 3)62 63 f(undefined, 3)64 }65 66 {67 // curried f & no initial arg63- const f2 = produce((state: {x:number}, increment: number): void => {68+ const f2 = produce((state: {x: number}, increment: number): void => {69 state.x += increment70 })71 67- f2({x : 5}, 3)72+ f2({x: 5}, 3)73 74 // $ExpectError75 f2(undefined, 3)76 }added:__tests__/recursive.js+187 added
1+"use strict"2+import produce, {setUseProxies} from "../src/immer"3+import {isArray, isPlainObject, isString, keys, trim} from "lodash"4+5+const nonPlainObject = () => {}6+7+runTests("proxy", true)8+runTests("es5", false)9+10+function runTests(name, useProxies) {11+ describe("recursive - " + name, () => {12+ setUseProxies(useProxies)13+14+ const testCases = [15+ {16+ title: "in a simple non-recursive case",17+ recursiveTransform: recursivelyTrimStrings,18+ baseState: " hello ",19+ desiredState: "hello"20+ },21+ {22+ title: "in a simple non-recursive unchanged case",23+ recursiveTransform: recursivelyTrimStrings,24+ baseState: "hello",25+ desiredState: "hello"26+ },27+ {28+ title: "if baseState is an object that does not change",29+ recursiveTransform: recursivelyTrimStrings,30+ baseState: {31+ a: 1,32+ b: "test",33+ c: {34+ a: [true, null, false, "test"],35+ b: 136+ }37+ }38+ },39+ {40+ title: "if baseState is an array does not change",41+ recursiveTransform: recursivelyTrimStrings,42+ baseState: [true, null, false, "test"]43+ },44+ {45+ title: "when all leafs are changing",46+ recursiveTransform: recursivelyTrimStrings,47+ baseState: {48+ x: " hello ",49+ arr: [50+ "world ",51+ 42,52+ " !!!",53+ {54+ x: 42,55+ test: "true "56+ }57+ ]58+ },59+ desiredState: {60+ x: "hello",61+ arr: [62+ "world",63+ 42,64+ "!!!",65+ {66+ x: 42,67+ test: "true"68+ }69+ ]70+ }71+ },72+ {73+ title: "when there is an unchanged leaf array",74+ recursiveTransform: recursivelyTrimStrings,75+ baseState: {76+ x: " hello ",77+ arr: [1, 2, 3]78+ },79+ desiredState: {80+ x: "hello",81+ arr: [1, 2, 3]82+ }83+ },84+ {85+ title:86+ "when there is an unchanged leaf object in an unchanged array",87+ recursiveTransform: recursivelyTrimStrings,88+ baseState: {89+ arr: [90+ "!!!",91+ {92+ x: 42,93+ y: "test"94+ }95+ ]96+ },97+ desiredState: {98+ arr: [99+ "!!!",100+ {101+ x: 42,102+ y: "test"103+ }104+ ]105+ }106+ },107+ {108+ title:109+ "when there is an unchanged leaf object in a changed array",110+ recursiveTransform: recursivelyTrimStrings,111+ baseState: {112+ arr: [113+ " !!!",114+ {115+ x: 42,116+ y: "test"117+ }118+ ]119+ },120+ desiredState: {121+ arr: [122+ "!!!",123+ {124+ x: 42,125+ y: "test"126+ }127+ ]128+ }129+ },130+ {131+ title:132+ "when there is an unchanged leaf array in a changed object",133+ recursiveTransform: recursivelyTrimStrings,134+ baseState: {135+ test: "!!! ",136+ arr: [1, 2, 3]137+ },138+ desiredState: {139+ test: "!!!",140+ arr: [1, 2, 3]141+ }142+ },143+ {144+ title: "when there non-plain objects",145+ recursiveTransform: recursivelyTrimStrings,146+ baseState: {147+ a: [nonPlainObject, 1],148+ b: nonPlainObject149+ }150+ }151+ ]152+153+ testCases154+ .slice(0, 9)155+ .forEach(({title, baseState, desiredState, recursiveTransform}) => {156+ it(`should not leave drafts ${title}`, () => {157+ const next = recursiveTransform(baseState)158+ if (desiredState) {159+ // an exception is thrown during deep comparison if any of the drafts is not finalized160+ expect(next).toEqual(desiredState)161+ } else {162+ expect(next).toBe(baseState)163+ }164+ })165+ })166+ })167+}168+169+function recursivelyTrimStrings(source) {170+ if (isString(source)) {171+ return trim(source)172+ } else if (isArray(source)) {173+ return produce(source, draft =>174+ draft.forEach((el, i) => {175+ const v = recursivelyTrimStrings(el)176+ draft[i] = v177+ })178+ )179+ } else if (isPlainObject(source)) {180+ return produce(source, draft => {181+ keys(draft).forEach(key => {182+ draft[key] = recursivelyTrimStrings(draft[key])183+ })184+ })185+ }186+ return source187+}modified:src/es5.js+7 added-1 removed
97 unmodified lines98 99 function assertUnfinished(state) {100 if (state.finished === true)101 throw new Error(102- "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"102+ "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " +103+ JSON.stringify(state.copy || state.base)104 )105 }106 107 // this sounds very expensive, but actually it is not that expensive in practice36 unmodified lines144 return false145 }146 147 export function produceEs5(baseState, producer) {148+ if (isProxy(baseState)) {149+ // See #100, don't nest producers150+ const returnValue = producer.call(baseState, baseState)151+ return returnValue === undefined ? baseState : returnValue152+ }153 const prevStates = states154 states = []155 try {156 // create proxy for root60 unmodified linesmodified:src/proxy.js+6 added
118 unmodified linesExpand all11912012112212312412512612712812913013113213313413513613713813914014125 unmodified lines118 unmodified linesExpand all}
// creates a proxy for plain objects / arraysfunction createProxy(parentState, base) { if (isProxy(base)) throw new Error("Immer bug. Plz report.") const state = createState(parentState, base) const proxy = Array.isArray(base) ? Proxy.revocable([state], arrayTraps) : Proxy.revocable(state, objectTraps) proxies.push(proxy) return proxy.proxy}
export function produceProxy(baseState, producer) { if (isProxy(baseState)) { // See #100, don't nest producers const returnValue = producer.call(baseState, baseState) return returnValue === undefined ? baseState : returnValue } const previousProxies = proxies proxies = [] try { // create proxy for root25 unmodified linesmodified:package.json+1 added
7 unmodified lines8 "jsnext:main": "dist/immer.module.js",9 "react-native": "dist/immer.module.js",10 "types": "./dist/immer.d.ts",11 "scripts": {12+ "watch": "jest --watch",13 "test": "jest",14 "test:perf": "yarn-or-npm build && node --expose-gc node_modules/jest-cli/bin/jest.js --verbose --testRegex '__performance_tests__/.*?js$'",15 "test:flow": "yarn-or-npm flow check",16 "coveralls": "jest --coverage && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage",70 unmodified linesmodified:readme.md+114 added-136 removed
1 # Immer2 3-[](https://www.npmjs.com/package/immer)4-[](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)5-[](https://travis-ci.org/mweststrate/immer)6-[](https://coveralls.io/github/mweststrate/immer?branch=master)7-[](https://github.com/prettier/prettier)8-[](https://www.paypal.me/michelweststrate)3+[](https://www.npmjs.com/package/immer) [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js) [](https://travis-ci.org/mweststrate/immer) [](https://coveralls.io/github/mweststrate/immer?branch=master) [](https://github.com/prettier/prettier) [](https://www.paypal.me/michelweststrate)4 5 _Create the next immutable state tree by simply modifying the current tree_6 7 ---8 9 * NPM: `npm install immer`10 * Yarn: `yarn add immer`11 * CDN: Exposed global is `immer`17- * Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`18- * JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`12+ * Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`13+ * JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`14 15 ---16 17 * Egghead lesson covering all of immer (7m): [Simplify creating immutable data trees with Immer](https://egghead.io/lessons/redux-simplify-creating-immutable-data-trees-with-immer)18 * Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)19 25-Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.26-It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.20+Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way. It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.21 28-The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_.29-Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state.30-This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.22+The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_. Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state. This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.23 24 25 26 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 unmodified lines51 }52 ]53 54 const nextState = produce(baseState, draftState => {63- draftState.push({ todo: "Tweet about it" })55+ draftState.push({todo: "Tweet about it"})56 draftState[1].done = true57 })58 ```59 34 unmodified lines94 ```javascript95 // Redux reducer96 // Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js97 const byId = (state, action) => {106- switch (action.type) {107- case RECEIVE_PRODUCTS:108- return {109- ...state,110- ...action.products.reduce((obj, product) => {111- obj[product.id] = product112- return obj113- }, {})114- }115- default:116- return state117- }98+ switch (action.type) {99+ case RECEIVE_PRODUCTS:100+ return {101+ ...state,102+ ...action.products.reduce((obj, product) => {103+ obj[product.id] = product104+ return obj105+ }, {})106+ }107+ default:108+ return state109+ }110 }111 ```112 113 After using Immer, that simply becomes:114 115 ```javascript124-import produce from 'immer'116+import produce from "immer"117 118 const byId = (state, action) =>127- produce(state, draft => {128- switch (action.type) {129- case RECEIVE_PRODUCTS:130- action.products.forEach(product => {131- draft[product.id] = product132- })133- }134- })119+ produce(state, draft => {120+ switch (action.type) {121+ case RECEIVE_PRODUCTS:122+ action.products.forEach(product => {123+ draft[product.id] = product124+ })125+ }126+ })127 ```128 129 Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.130 139-Creating Redux reducer is just a sample application of the Immer package.140-Immer is not just designed to simplify Redux reducers.141-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+Creating Redux reducer 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).132 133 _Note: it might be tempting after using producers for a while, to just place `produce` in your root reducer and then pass the draft to each reducer and work directly over such draft. Don't do that. It kills the point of Redux where each reducer is testable as pure reducer. Immer is best used when applying it to small individual pieces of logic._134 135 ## React.setState example136 147-Deep updates in the state of React components can be greatly simplified as well by using immer.148-Take for example the following onClick handlers (Try in [codesandbox](https://codesandbox.io/s/m4yp57632j)):137+Deep updates in the state of React components can be greatly simplified as well by using immer. Take for example the following onClick handlers (Try in [codesandbox](https://codesandbox.io/s/m4yp57632j)):138 139 ```javascript140 /**141 * Classic React.setState with a deep merge142 */143 onBirthDayClick1 = () => {155- this.setState((prevState)=>({144+ this.setState(prevState => ({145 user: {146 ...prevState.user,147 age: prevState.user.age + 1148 }2 unmodified lines151 152 /**153 * ...But, since setState accepts functions,154 * we can just create a curried producer and further simplify!166-*/155+ */156 onBirthDayClick2 = () => {157+ this.setState(168- this.setState(produce(draft => {169- draft.user.age += 1170- }))158+ produce(draft => {159+ draft.user.age += 1160+ })161+ )162 }163 ```164 165 ## Currying166 176-Passing a function as the first argument to `produce` is intended to be used for currying. This means that you get a pre-bound producer that only needs a state to produce the value from.177-The producer function gets passed in the draft, and any further arguments that were passed to the curried function.167+Passing a function as the first argument to `produce` is intended to be used for currying. This means that you get a pre-bound producer that only needs a state to produce the value from. The producer function gets passed in the draft, and any further arguments that were passed to the curried function.168 169 For example:170 171 ```javascript28 unmodified lines200 201 If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:202 203 ```javascript214-import produce from 'immer'204+import produce from "immer"205 206 const byId = produce(217- (draft, action) => {218- switch (action.type) {219- case RECEIVE_PRODUCTS:220- action.products.forEach(product => {221- draft[product.id] = product222- })223- return207+ (draft, action) => {208+ switch (action.type) {209+ case RECEIVE_PRODUCTS:210+ action.products.forEach(product => {211+ draft[product.id] = product212+ })213+ return214+ }215+ },216+ {217+ 1: {id: 1, name: "product-1"}218 }225- },226- {227- 1: { id: 1, name: "product-1" }228- }219 )220 ```221 222 ## Auto freezing223 234- Immer automatically freezes any state trees that are modified using `produce`.235- This protects against accidental modifications of the state tree outside of a producer.236- This comes with a performance impact, so it is recommended to disable this option in production.237- It is by default enabled.238- By default it is turned on during local development, and turned off in production.239- Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.224+Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default it is turned on during local development, and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.225 226 ## Returning data from producers227 243-It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway.244-However, it is allowed to just `return draft`.228+It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway. However, it is allowed to just `return draft`.229 246-It is also allowed to return arbitrarily other data from the producer function. But _only_ if you didn't modify the draft.247-This can be useful to produce an entirely new state. Some examples:230+It is also allowed to return arbitrarily other data from the producer function. But _only_ if you didn't modify the draft. This can be useful to produce an entirely new state. Some examples:231 232 ```javascript233 const userReducer = produce((draft, action) => {251- switch (action.type) {252- case "renameUser":253- // OK: we modify the current state254- draft.users[action.payload.id].name = action.payload.name255- return draft // same as just 'return'256- case "loadUsers":257- // OK: we return an entirely new state258- return action.payload259- case "adduser-1":260- // NOT OK: This doesn't do change the draft nor return a new state!261- // It doesn't modify the draft (it just redeclares it)262- // In fact, this just doesn't do anything at all263- draft = { users: [...draft.users, action.payload]}264- return265- case "adduser-2":266- // NOT OK: modifying draft *and* returning a new state267- draft.userCount += 1268- return { users: [...draft.users, action.payload] }269- case "adduser-3":270- // OK: returning a new state. But, unnecessary complex and expensive271- return {272- userCount: draft.userCount + 1,273- users: [...draft.users, action.payload]274- }275- case "adduser-4":276- // OK: the immer way277- draft.userCount += 1278- draft.users.push(action.payload)279- return280- }234+ switch (action.type) {235+ case "renameUser":236+ // OK: we modify the current state237+ draft.users[action.payload.id].name = action.payload.name238+ return draft // same as just 'return'239+ case "loadUsers":240+ // OK: we return an entirely new state241+ return action.payload242+ case "adduser-1":243+ // NOT OK: This doesn't do change the draft nor return a new state!244+ // It doesn't modify the draft (it just redeclares it)245+ // In fact, this just doesn't do anything at all246+ draft = {users: [...draft.users, action.payload]}247+ return248+ case "adduser-2":249+ // NOT OK: modifying draft *and* returning a new state250+ draft.userCount += 1251+ return {users: [...draft.users, action.payload]}252+ case "adduser-3":253+ // OK: returning a new state. But, unnecessary complex and expensive254+ return {255+ userCount: draft.userCount + 1,256+ users: [...draft.users, action.payload]257+ }258+ case "adduser-4":259+ // OK: the immer way260+ draft.userCount += 1261+ draft.users.push(action.payload)262+ return263+ }264 })265 ```266 267 ## Using `this`2 unmodified lines270 271 This means that the following constructions are also valid:272 273 ```javascript291-const base = { counter: 0 }274+const base = {counter: 0}275 276 const next = produce(base, function() {294- this.counter++277+ this.counter++278 })279 console.log(next.counter) // 1280 281 // OR282 const increment = produce(function() {300- this.counter++283+ this.counter++284 })285 console.log(increment(base).counter) // 1286 ```287 2 unmodified lines290 The Immer package ships with type definitions inside the package, which should be picked up by TypeScript and Flow out of the box and without further configuration.291 292 ## Immer on older JavaScript environments?293 311-By default `produce` tries to use proxies for optimal performance.312-However, on older JavaScript engines `Proxy` is not available.313-For example, when running Microsoft Internet Explorer or React Native on Android.314-In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.294+By default `produce` tries to use proxies for optimal performance. However, on older JavaScript engines `Proxy` is not available. For example, when running Microsoft Internet Explorer or React Native on Android. In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.295 296 ## Pitfalls297 298 1. Don't redefine draft like, `draft = myCoolNewState`. Instead, either modify the `draft` or return a new state. See [Returning data from producers](#returning-data-from-producers).299 1. Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.320-2. 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), the changes will be persisted. But, both in your new and old state! So, in such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.321-3. For example, working with `Date` objects is no problem, just make sure you never modify them (by using methods like `setYear` on an existing instance). Instead, always create fresh `Date` instances. Which is probably what you were unconsciously doing already.322-4. 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`323-5. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.300+1. 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), the changes will be persisted. But, both in your new and old state! So, in such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.301+1. For example, working with `Date` objects is no problem, just make sure you never modify them (by using methods like `setYear` on an existing instance). Instead, always create fresh `Date` instances. Which is probably what you were unconsciously doing already.302+1. 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`303+1. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.304 305 ## Cool things built with immer306 307 * [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_10 unmodified lines318 319 _For those who have to go back to thinking in object updates :-)_320 321 ```javascript342-import produce from "immer";322+import produce from "immer"323 324 // object mutations325 const todosObj = {346- id1: { done: false, body: "Take out the trash" },347- id2: { done: false, body: "Check Email" }348-};326+ id1: {done: false, body: "Take out the trash"},327+ id2: {done: false, body: "Check Email"}328+}329 330 // add331 const addedTodosObj = produce(todosObj, draft => {352- draft["id3"] = { done: false, body: "Buy bananas" };353-});332+ draft["id3"] = {done: false, body: "Buy bananas"}333+})334 335 // delete336 const deletedTodosObj = produce(todosObj, draft => {357- delete draft["id1"];358-});337+ delete draft["id1"]338+})339 340 // update341 const updatedTodosObj = produce(todosObj, draft => {362- draft["id1"].done = true;363-});342+ draft["id1"].done = true343+})344 345 // array mutations346 const todosArray = [367- { id: "id1", done: false, body: "Take out the trash" },368- { id: "id2", done: false, body: "Check Email" }369-];347+ {id: "id1", done: false, body: "Take out the trash"},348+ {id: "id2", done: false, body: "Check Email"}349+]350 351 // add352 const addedTodosArray = produce(todosArray, draft => {373- draft.push({ id: "id3", done: false, body: "Buy bananas" });374-});353+ draft.push({id: "id3", done: false, body: "Buy bananas"})354+})355 356 // delete357 const deletedTodosArray = produce(todosArray, draft => {378- draft.splice(draft.findIndex(todo => todo.id === "id1"), 1);379- // or (slower):380- // return draft.filter(todo => todo.id !== "id1")381-});358+ draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)359+ // or (slower):360+ // return draft.filter(todo => todo.id !== "id1")361+})362 363 // update364 const updatedTodosArray = produce(todosArray, draft => {385- draft[draft.findIndex(todo => todo.id === "id1")].done = true;386-});365+ draft[draft.findIndex(todo => todo.id === "id1")].done = true366+})367 ```368 369 ## Performance370 391-Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer.392-This test takes 100.000 todo items, and updates 10.000 of them.393-_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.371+Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer. This test takes 100.000 todo items, and updates 10.000 of them. _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.372 395-These tests were executed on Node 8.4.0.396-Use `yarn test:perf` to reproduce them locally.373+These tests were executed on Node 8.4.0. Use `yarn test:perf` to reproduce them locally.374 375 376 377 Some observations:378+379 * From `immer` perspective, this benchmark is a _worst case_ scenario, because the root collection it has to proxy is really large relatively to the rest of the data set.380 * 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).381 * 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.382 * Immer with proxies is roughly speaking twice as slow as a hand written reducer. This is in practice negligible.43 unmodified lines