Skip to content
Myr

Merge branch 'master' into 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 3069aaa, 41bb8b9 · Browse files · 12 files+214 added−189 removed
This commit

State

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

Diff stats

12 files+214 added−189 removed

  • tests:+52 added−20 removed
  • other:+162 added−169 removed

12 files+214 added−189 removed

modified:__tests__/flow/flow.js.flow+24 added-10 removed
12 unmodified lines
13})1415console.log(result.x)1617const f2 = produce(draft => {})17const result2 = produce({x: 3}, draft => {18 return {x: 4}19})2021console.log(result2.x)2223const f = produce((draft): {x: number} => {24 return {x: 4}25})26f({x: 3})2728const f2 = produce((draft): void => {})29f2({x: 3})3031// $ExpectError32setAutoFreeze(3)
11 unmodified lines
44produce({x: 3}, [])4546{47 // curried & initial arg37 const f = produce((state, increment: number) => {38 state.x += increment39 }, { x: 3})48 const f = produce(49 (state, increment: number): void => {50 state.x += increment51 },52 {x: 3}53 )5455 // $ExpectError Too few arguments42 f({x : 5})56 f({x: 5})5758 // $ExpectError45 f({x : 5}, "test")59 f({x: 5}, "test")6047 f({x : 5}, 3)61 f({x: 5}, 3)6263 f(undefined, 3)64}6566{67 // curried f & no initial arg54 const f2 = produce((state: {x:number}, increment: number) => {68 const f2 = produce((state: {x: number}, increment: number): void => {69 state.x += increment70 })7158 f2({x : 5}, 3)72 f2({x: 5}, 3)7374 // $ExpectError75 f2(undefined, 3)62}76}
modified:__tests__/flow/ts.ts+27 added-9 removed
modified:__tests__/base.js+1 added-1 removed
722 unmodified lines
723 if (useProxies)724 it("should not allow changing prototype", () => {725 produce({}, draft => {726 expect(() => Object.setPrototypeOf(draft, Array)).toThrow(727 /try this/727 /does not support `setPrototype/728 )729 })730 })731
205 unmodified lines
modified:src/common.js+13 added-3 removed
52 unmodified lines
53 }54 return value55}5657const assign =58 Object.assign ||59 function assign(target, value) {60 for (let key in value) {61 if (has(value, key)) {62 target[key] = value[key]63 }64 }65 return target66 }6768export function shallowCopy(value) {69 if (Array.isArray(value)) return value.slice()59 if (value.__proto__ === undefined)60 return Object.assign(Object.create(null), value)61 return Object.assign({}, value)70 const target = value.__proto__ === undefined ? Object.create(null) : {}71 return assign(target, value)72}7374export function each(value, cb) {75 if (Array.isArray(value)) {
69 unmodified lines
modified:src/es5.js+1 added-1 removed
102 unmodified lines
103 JSON.stringify(state.copy || state.base)104 )105}106107// this sounds very expensive, but actually it is not that extensive in practice107// this sounds very expensive, but actually it is not that expensive in practice108// as it will only visit proxies, and only do key-based change detection for objects for109// which it is not already know that they are changed (that is, only object for which no known key was changed)110function markChanges() {111 // intentionally we process the proxies in reverse order;
105 unmodified lines
modified:src/immer.d.ts+11 added-11 removed
modified:src/immer.js.flow+11 added-11 removed
13 unmodified lines
14 * @returns The next state: a new state, or the current state if nothing was modified15 */16declare export default function produce<S>(17 currentState: S,18 recipe: (draftState: S) => void18 recipe: (draftState: S) => S | void19): S20// curried invocations with inital state21declare export default function produce<S, A, B, C>(22 recipe: (draftState: S, a: A, b: B, c: C) => void,22 recipe: (draftState: S, a: A, b: B, c: C) => S | void,23 initialState: S24): (currentState: S | void, a: A, b: B, c: C) => S25declare export default function produce<S, A, B>(26 recipe: (draftState: S, a: A, b: B) => void,26 recipe: (draftState: S, a: A, b: B) => S | void,27 initialState: S28): (currentState: S | void, a: A, b: B) => S29declare export default function produce<S, A>(30 recipe: (draftState: S, a: A) => void,30 recipe: (draftState: S, a: A) => S | void,31 initialState: S32): (currentState: S | void, a: A) => S33declare export default function produce<S>(34 recipe: (draftState: S) => void,34 recipe: (draftState: S) => S | void,35 initialState: S36): (currentState: S | void) => S37declare export default function produce<S>(38 recipe: (draftState: S, ...extraArgs: any[]) => void,38 recipe: (draftState: S, ...extraArgs: any[]) => S | void,39 initialState: S40): (currentState: S | void, ...extraArgs: any[]) => S41// curried invocations without inital state42declare export default function produce<S, A, B, C>(43 recipe: (draftState: S, a: A, b: B, c: C) => void43 recipe: (draftState: S, a: A, b: B, c: C) => S | void44): (currentState: S, a: A, b: B, c: C) => S45declare export default function produce<S, A, B>(46 recipe: (draftState: S, a: A, b: B) => void46 recipe: (draftState: S, a: A, b: B) => S | void47): (currentState: S, a: A, b: B) => S48declare export default function produce<S, A>(49 recipe: (draftState: S, a: A) => void49 recipe: (draftState: S, a: A) => S | void50): (currentState: S, a: A) => S51declare export default function produce<S>(52 recipe: (draftState: S) => void52 recipe: (draftState: S) => S | void53): (currentState: S) => S54declare export default function produce<S>(55 recipe: (draftState: S, ...extraArgs: any[]) => void55 recipe: (draftState: S, ...extraArgs: any[]) => S | void56): (currentState: S, ...extraArgs: any[]) => S57/**58 * Automatically freezes any state trees generated by immer.59 * This protects against accidental modifications of the state tree outside of an immer function.
10 unmodified lines
modified:src/proxy.js+2 added-2 removed
26 unmodified lines
27 deleteProperty,28 getOwnPropertyDescriptor,29 defineProperty,30 setPrototypeOf() {31 throw new Error("Don't even try this...")31 throw new Error("Immer does not support `setPrototypeOf()`.")32 }33}3435const arrayTraps = {}
67 unmodified lines
103}104105function defineProperty() {106 throw new Error(107 "Immer does currently not support defining properties on draft objects"107 "Immer does not support defining properties on draft objects."108 )109}110111function markChanged(state) {
55 unmodified lines
modified:changelog.md+4 added
1# Changelog23### 1.2.145* Improved TypeScript and Flow typings to support return a new state from a producer. Trough [#131](https://github.com/mweststrate/immer/pull/131) by [dmorosinotto](https://github.com/mweststrate/immer/issues?q=is%3Apr+author%3Admorosinotto) resp [#127](https://github.com/mweststrate/immer/pull/127) by [bugzpodder](https://github.com/mweststrate/immer/pull/127)67### 1.289* It is now possible to pass an _initial state_ to a _curried producer_. This makes it simpler to write Redux reducers that have a default initial state. See [#121](https://github.com/mweststrate/immer/pull/121) by (@pkerschbaum)[https://github.com/pkerschbaum]. Implements [#111](https://github.com/mweststrate/immer/issues/111).10* Improved TypeScript & Flow typings. See [#109]](https://github.com/mweststrate/immer/pull/109) by [ogwh](https://github.com/ogwh).
141 unmodified lines
modified:package.json+2 added-2 removed
1{2 "name": "immer",3 "version": "1.2.0",3 "version": "1.2.1",4 "description": "Create your next immutable state by mutating the current one",5 "main": "dist/immer.js",6 "umd:main": "dist/immer.umd.js",7 "module": "dist/immer.module.js",
42 unmodified lines
50 "coveralls": "^3.0.0",51 "cpx": "^1.5.0",52 "cross-env": "^5.1.3",53 "deep-freeze": "^0.0.1",54 "flow-bin": "^0.65.0",54 "flow-bin": "^0.68.0",55 "husky": "^0.14.3",56 "immutable": "^3.8.2",57 "jest": "^22.0.4",58 "lint-staged": "^6.1.0",
28 unmodified lines
modified:readme.md+115 added-136 removed
1# Immer23[![npm](https://img.shields.io/npm/v/immer.svg)](https://www.npmjs.com/package/immer)4[![size](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js?compression=gzip)](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)5[![Build Status](https://travis-ci.org/mweststrate/immer.svg?branch=master)](https://travis-ci.org/mweststrate/immer)6[![Coverage Status](https://coveralls.io/repos/github/mweststrate/immer/badge.svg?branch=master)](https://coveralls.io/github/mweststrate/immer?branch=master)7[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)8[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/michelweststrate)3[![npm](https://img.shields.io/npm/v/immer.svg)](https://www.npmjs.com/package/immer) [![size](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js?compression=gzip)](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js) [![Build Status](https://travis-ci.org/mweststrate/immer.svg?branch=master)](https://travis-ci.org/mweststrate/immer) [![Coverage Status](https://coveralls.io/repos/github/mweststrate/immer/badge.svg?branch=master)](https://coveralls.io/github/mweststrate/immer?branch=master) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.me/michelweststrate)45_Create the next immutable state tree by simply modifying the current tree_67---89* 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>`1415---1617* 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)1925Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.26It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.20Immer (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.2128The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_.29Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state.30This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.22The 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.2324![immer-hd.png](images/hd/immer.png)2526Using 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 lines
51 }52]5354const 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 lines
94```javascript95// Redux reducer96// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js97const 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```112113After using Immer, that simply becomes:114115```javascript124import produce from 'immer'116import produce from "immer"117118const 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```128129Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.130139Creating Redux reducer is just a sample application of the Immer package.140Immer is not just designed to simplify Redux reducers.141It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing).131Creating 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).132133_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._134135## React.setState example136147Deep updates in the state of React components can be greatly simplified as well by using immer.148Take for example the following onClick handlers (Try in [codesandbox](https://codesandbox.io/s/m4yp57632j)):137Deep 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)):138139```javascript140/**141 * Classic React.setState with a deep merge142 */143onBirthDayClick1 = () => {155 this.setState((prevState)=>({144 this.setState(prevState => ({145 user: {146 ...prevState.user,147 age: prevState.user.age + 1148 }
2 unmodified lines
151152/**153 * ...But, since setState accepts functions,154 * we can just create a curried producer and further simplify!166*/155 */156onBirthDayClick2 = () => {157 this.setState(168 this.setState(produce(draft => {169 draft.user.age += 1170 }))158 produce(draft => {159 draft.user.age += 1160 })161 )162}163```164165## Currying166176Passing 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.177The producer function gets passed in the draft, and any further arguments that were passed to the curried function.167Passing 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.168169For example:170171```javascript
28 unmodified lines
200201If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:202203```javascript214import produce from 'immer'204import produce from "immer"205206const 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```221222## Auto freezing223234 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.224Immer 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.225226## Returning data from producers227243It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway.244However, it is allowed to just `return draft`.228It 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`.229246It is also allowed to return arbitrarily other data from the producer function. But _only_ if you didn't modify the draft.247This can be useful to produce an entirely new state. Some examples:230It 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:231232```javascript233const 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.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```266267## Using `this`
2 unmodified lines
270271This means that the following constructions are also valid:272273```javascript291const base = { counter: 0 }274const base = {counter: 0}275276const next = produce(base, function() {294 this.counter++277 this.counter++278})279console.log(next.counter) // 1280281// OR282const increment = produce(function() {300 this.counter++283 this.counter++284})285console.log(increment(base).counter) // 1286```287
2 unmodified lines
290The 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.291292## Immer on older JavaScript environments?293311By default `produce` tries to use proxies for optimal performance.312However, on older JavaScript engines `Proxy` is not available.313For example, when running Microsoft Internet Explorer or React Native on Android.314In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.294By 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.295296## Pitfalls2972981. 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).2991. Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.3202. 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.3213. 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.3224. 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`3235. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.3001. 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.3011. 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.3021. 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`3031. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.304305## Cool things built with immer306307* [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_308* [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_309* [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_310* [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux developement quicker and easier_311* [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_312313## How does Immer work?314315Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).
2 unmodified lines
318319_For those who have to go back to thinking in object updates :-)_320321```javascript341import produce from "immer";322import produce from "immer"323324// object mutations325const todosObj = {345 id1: { done: false, body: "Take out the trash" },346 id2: { done: false, body: "Check Email" }347};326 id1: {done: false, body: "Take out the trash"},327 id2: {done: false, body: "Check Email"}328}329330// add331const addedTodosObj = produce(todosObj, draft => {351 draft["id3"] = { done: false, body: "Buy bananas" };352});332 draft["id3"] = {done: false, body: "Buy bananas"}333})334335// delete336const deletedTodosObj = produce(todosObj, draft => {356 delete draft["id1"];357});337 delete draft["id1"]338})339340// update341const updatedTodosObj = produce(todosObj, draft => {361 draft["id1"].done = true;362});342 draft["id1"].done = true343})344345// array mutations346const todosArray = [366 { id: "id1", done: false, body: "Take out the trash" },367 { id: "id2", done: false, body: "Check Email" }368];347 {id: "id1", done: false, body: "Take out the trash"},348 {id: "id2", done: false, body: "Check Email"}349]350351// add352const addedTodosArray = produce(todosArray, draft => {372 draft.push({ id: "id3", done: false, body: "Buy bananas" });373});353 draft.push({id: "id3", done: false, body: "Buy bananas"})354})355356// delete357const deletedTodosArray = produce(todosArray, draft => {377 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1);378 // or (slower):379 // return draft.filter(todo => todo.id !== "id1")380});358 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)359 // or (slower):360 // return draft.filter(todo => todo.id !== "id1")361})362363// update364const updatedTodosArray = produce(todosArray, draft => {384 draft[draft.findIndex(todo => todo.id === "id1")].done = true;385});365 draft[draft.findIndex(todo => todo.id === "id1")].done = true366})367```368369## Performance370390Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer.391This test takes 100.000 todo items, and updates 10.000 of them.392_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.371Here 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.372394These tests were executed on Node 8.4.0.395Use `yarn test:perf` to reproduce them locally.373These tests were executed on Node 8.4.0. Use `yarn test:perf` to reproduce them locally.374375![performance.png](images/performance.png)376377Some observations:378379* 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
modified:yarn.lock+3 added-3 removed
1563 unmodified lines
1564 resolved "https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7"1565 dependencies:1566 locate-path "^2.0.0"15671568flow-bin@^0.65.0:1569 version "0.65.0"1570 resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.65.0.tgz#64ffeca27211c786e2d68508c65686ba1b8a2169"1568flow-bin@^0.68.0:1569 version "0.68.0"1570 resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.68.0.tgz#86c2d14857d306eb2e85e274f2eebf543564f623"15711572for-in@^1.0.1:1573 version "1.0.2"1574 resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80"
2847 unmodified lines