Skip to content
Myr

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

10 files+69 added−70 removed

modified:__performance_tests__/todo.js+6 added-6 removed
modified:__tests__/base.js+28 added-28 removed
8 unmodified lines
9runBaseTest("es5 (autofreeze)", immerEs5, true)1011function runBaseTest(name, lib, freeze) {12 describe(`base functionality - ${name}`, () => {13 const immer = lib.default13 const produce = lib.default14 let baseState15 let origBaseState1617 beforeEach(() => {
1 unmodified line
19 origBaseState = baseState = createBaseState()20 })2122 it("should return the original without modifications", () => {23 const nextState = immer(baseState, () => {})23 const nextState = produce(baseState, () => {})24 expect(nextState).toBe(baseState)25 })2627 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 })3435 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, () => "")4142 expect(warning).toHaveBeenCalledTimes(4)43 warning.mockClear()44 })4546 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 lines
5657 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 lines
69 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 lines
80 expect(nextState.anArray).toBe(baseState.anArray)81 })8283 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 line
90 expect(nextState.anObject.cookie).toEqual({tasty: true})91 })9293 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 })101102 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 })108109 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 })117118 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 })125126 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 })134135 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 lines
148 ])149 })150151 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 line
158 expect(nextState.anArray).toEqual([3, 2, {c: 3}])159 })160161 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 lines
169 expect(enumerableOnly(nextState.anArray)).toEqual([1, 2, 3, {c: 5}])170 })171172 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 lines
191 })192 })193194 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 = 5
11 unmodified lines
211 ])212 })213214 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 })222223 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 lines
241 expect(nextState.messy.nested).toBe(baseState.anObject.nested)242 })243244 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 = true
15 unmodified lines
265 expect(nextState.messy.nested).toBe(baseState.anObject.nested)266 })267268 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 lines
277 // 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 lines
300 }301302 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 lines
314 }).toThrowError(/revoked/)315 })316317 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 lines
modified:__tests__/frozen.js+4 added-4 removed
6 unmodified lines
7runTests("es5", immerEs5)89function 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 }1617 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 lines
29 })3031 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 lines
46 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 lines
modified:__tests__/readme.js+2 added-2 removed
1"use strict"2import immer from ".."2import produce from ".."34describe("readme example", () => {5 it("works", () => {6 const baseState = [
6 unmodified lines
13 done: false14 }15 ]1617 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 lines
modified: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# Changelog23### 0.3.145* Republished, somehow NPM still returned 0.2.267### 0.3.0 (8-1-2018)89* 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 lines
modified: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 lines
modified:readme.md+23 added-29 removed
14 unmodified lines
15Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.16It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.1718The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_.19Once all your mutations are completed, immer will produce the _nextState_ based on the mutations to the draft state.19Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state.20This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.2122![immer.png](images/immer.png)2324Using 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).24Using 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).2526A 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.2728## Installation2930`npm install immer`3128## API2934The immer package exposes a default function that does all the work.30The Immer package exposes a default function that does all the work.3136`immer(currentState, fn: (draftState) => void): nextState`32`produce(currentState, producer: (draftState) => void): nextState`3334There is also a curried overload that is explained [below](#currying)3536## Example3738```javascript43import immer from "immer"39import produce from "immer"4041const baseState = [42 {43 todo: "Learn typescript",
4 unmodified lines
48 done: false49 }50]5156const nextState = immer(baseState, draftState => {52const nextState = produce(baseState, draftState => {53 draftState.push({ todo: "Tweet about it" })54 draftState[1].done = true55})56```5762The interesting thing about `immer` is that, the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.58The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.5960```javascript61// the new item is only added to the next state,62// base state is unmodified
24 unmodified lines
87## Reducer Example8889Here is a simple example of the difference that Immer could make in practice.909591```javascript92// Redux reducer93// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js94const byId = (state, action) => {
11 unmodified lines
106 }107}108```109115After using immer, that simply becomes:110After using Immer, that simply becomes:111112```javascript118import immer from 'immer'113import produce from 'immer'114115const byId = (state, action) =>116 produce(state, draft => {117 switch (action.type) {
6 unmodified lines
124```125126Note that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.127133_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.129Immer is not just designed to simplify Redux reducers.130It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing)_131132## Currying
17 unmodified lines
150151This mechanism can also nicely be leveraged to further simplify our example reducer:152153```javascript159154const byId = produce((draft, action) => {155 switch (action.type) {156 case RECEIVE_PRODUCTS:157 action.products.forEach(product => {
9 unmodified lines
167168## Auto freezing169170 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.175182## Using immer on older JavaScript environments176## Using Immer on older JavaScript environments177184By default `immer` tries to use proxies for optimal performance.178By default `produce` tries to use proxies for optimal performance.179However, on older JavaScript engines `Proxy` is not available.180For example, Microsoft Internet Explorer or React Native on Android.181In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:182
2 unmodified lines
185```186187## More reducer examples188195Here 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.189Here 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.190These examples are semantically equivalent and produce the exact same state.191192```javascript193// Plain reducer
6 unmodified lines
200}201202// With immer203function 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 lines
215}216217// With immer218function removeItem(array, action) {225 return immer(array, draft => {219 return produce(array, draft => {220 draft.splice(action.index, 1)221 })222}223
14 unmodified lines
238}239240// With immer241function 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 lines
250## Pitfalls251252* 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.256263## How does immer work?257## How does Immer work?258259Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/9d73d8f71cb3).260261## Performance262269Here is a [simple benchmark](__tests__/performance.js) on the performance of `immer`.263Here is a [simple benchmark](__tests__/performance.js) on the performance of Immer.264This 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.266267These tests were executed on Node 8.4.0.
2 unmodified lines
270![performance.png](images/performance.png)271272Some 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.279280## Credits281
5 unmodified lines