Skip to content
Myr

Merge branch 'travis' of https://github.com/Gregjarvez/immer into travis

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

authored by Gregory Assasie · committed by Gregory Assasie · parents 70eee19, 0ad65c6 · Browse files · 7 files+607 added−217 removed
This commit

State

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

Diff stats

7 files+607 added−217 removed

  • tests:+237 added−206 removed
  • other:+370 added−11 removed

7 files+607 added−217 removed

modified:__tests__/base.js+209 added-198 removed
1"use strict"2import immer from ".."2import immerProxy from ".."3import immerEs5 from "../es5"44describe("base", () => {5 let baseState6 let origBaseState5runBaseTest("proxy", immerProxy)6runBaseTest("es5", immerEs5)78 beforeEach(() => {9 origBaseState = baseState = createBaseState()10 })8function runBaseTest(name, immer) {9 describe(`base functionality - ${name}`, () => {10 let baseState11 let origBaseState1212 it("should return the original without modifications", () => {13 const nextState = immer(baseState, () => {})14 expect(nextState).toBe(baseState)15 })13 beforeEach(() => {14 origBaseState = baseState = createBaseState()15 })1617 it("should return the original without modifications when reading stuff", () => {18 const nextState = immer(baseState, s => {19 expect(s.aProp).toBe("hi")20 expect(s.anObject.nested).toEqual({yummie: true})17 it("should return the original without modifications", () => {18 const nextState = immer(baseState, () => {})19 expect(nextState).toBe(baseState)20 })22 expect(nextState).toBe(baseState)23 })2125 it("should not return any value: thunk", () => {26 const warning = jest.spyOn(console, "warn")27 immer(baseState, () => ({bad: "don't do this"}))28 immer(baseState, () => [1, 2, 3])29 immer(baseState, () => false)30 immer(baseState, () => "")22 it("should return the original without modifications when reading stuff", () => {23 const nextState = immer(baseState, s => {24 expect(s.aProp).toBe("hi")25 expect(s.anObject.nested).toMatchObject({yummie: true})26 })27 expect(nextState).toBe(baseState)28 })2932 expect(warning).toHaveBeenCalledTimes(4)33 })30 it("should not return any value: thunk", () => {31 const warning = jest.spyOn(console, "warn")32 immer(baseState, () => ({bad: "don't do this"}))33 immer(baseState, () => [1, 2, 3])34 immer(baseState, () => false)35 immer(baseState, () => "")3635 it("should return a copy when modifying stuff", () => {36 const nextState = immer(baseState, s => {37 s.aProp = "hello world"37 expect(warning).toHaveBeenCalledTimes(4)38 warning.mockClear()39 })39 expect(nextState).not.toBe(baseState)40 expect(baseState.aProp).toBe("hi")41 expect(nextState.aProp).toBe("hello world")42 // structural sharing?43 expect(nextState.nested).toBe(baseState.nested)44 })4046 it("deep change bubbles up", () => {47 const nextState = immer(baseState, s => {48 s.anObject.nested.yummie = false41 it("should return a copy when modifying stuff", () => {42 const nextState = immer(baseState, s => {43 s.aProp = "hello world"44 })45 expect(nextState).not.toBe(baseState)46 expect(baseState.aProp).toBe("hi")47 expect(nextState.aProp).toBe("hello world")48 // structural sharing?49 expect(nextState.nested).toBe(baseState.nested)50 })50 expect(nextState).not.toBe(baseState)51 expect(nextState.anObject).not.toBe(baseState.anObject)52 expect(baseState.anObject.nested.yummie).toBe(true)53 expect(nextState.anObject.nested.yummie).toBe(false)54 expect(nextState.anArray).toBe(baseState.anArray)55 })5157 it("can add props", () => {58 const nextState = immer(baseState, s => {59 s.anObject.cookie = {tasty: true}52 it("deep change bubbles up", () => {53 const nextState = immer(baseState, s => {54 s.anObject.nested.yummie = false55 })56 expect(nextState).not.toBe(baseState)57 expect(nextState.anObject).not.toBe(baseState.anObject)58 expect(baseState.anObject.nested.yummie).toBe(true)59 expect(nextState.anObject.nested.yummie).toBe(false)60 expect(nextState.anArray).toBe(baseState.anArray)61 })61 expect(nextState).not.toBe(baseState)62 expect(nextState.anObject).not.toBe(baseState.anObject)63 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)64 expect(nextState.anObject.cookie).toEqual({tasty: true})65 })6267 it("can delete props", () => {68 const nextState = immer(baseState, s => {69 delete s.anObject.nested63 it("can add props", () => {64 const nextState = immer(baseState, s => {65 s.anObject.cookie = {tasty: true}66 })67 expect(nextState).not.toBe(baseState)68 expect(nextState.anObject).not.toBe(baseState.anObject)69 expect(nextState.anObject.nested).toBe(baseState.anObject.nested)70 expect(nextState.anObject.cookie).toEqual({tasty: true})71 })71 expect(nextState).not.toBe(baseState)72 expect(nextState.anObject).not.toBe(baseState.anObject)73 expect(nextState.anObject.nested).toBe(undefined)74 })7276 it("ignores single non-modification", () => {77 const nextState = immer(baseState, s => {78 s.aProp = "hi"73 it("can delete props", () => {74 const nextState = immer(baseState, s => {75 delete s.anObject.nested76 })77 expect(nextState).not.toBe(baseState)78 expect(nextState.anObject).not.toBe(baseState.anObject)79 expect(nextState.anObject.nested).toBe(undefined)80 })80 expect(nextState).toBe(baseState)81 })8183 it("processes single modification", () => {84 const nextState = immer(baseState, s => {85 s.aProp = "hello"86 s.aProp = "hi"82 it("ignores single non-modification", () => {83 const nextState = immer(baseState, s => {84 s.aProp = "hi"85 })86 expect(nextState).toBe(baseState)87 })88 expect(nextState).not.toBe(baseState)89 expect(nextState).toEqual(baseState)90 })8892 it("should support reading arrays", () => {93 const nextState = immer(baseState, s => {94 s.anArray.slice()89 it("processes single modification", () => {90 const nextState = immer(baseState, s => {91 s.aProp = "hello"92 s.aProp = "hi"93 })94 expect(nextState).not.toBe(baseState)95 expect(nextState).toEqual(baseState)96 })96 expect(nextState.anArray).toBe(baseState.anArray)97 expect(nextState).toBe(baseState)98 })97100 it("should support changing arrays", () => {101 const nextState = immer(baseState, s => {102 s.anArray[3] = true98 it("should support reading arrays", () => {99 const nextState = immer(baseState, s => {100 s.anArray.slice()101 })102 expect(nextState.anArray).toBe(baseState.anArray)103 expect(nextState).toBe(baseState)104 })104 expect(nextState).not.toBe(baseState)105 expect(nextState.anArray).not.toBe(baseState.anArray)106 expect(nextState.anArray[3]).toEqual(true)107 })105109 it("should support changing arrays - 2", () => {110 const nextState = immer(baseState, s => {111 s.anArray.splice(1, 1, "a", "b")106 it("should support changing arrays", () => {107 const nextState = immer(baseState, s => {108 s.anArray[3] = true109 })110 expect(nextState).not.toBe(baseState)111 expect(nextState.anArray).not.toBe(baseState.anArray)112 expect(nextState.anArray[3]).toEqual(true)113 })113 expect(nextState).not.toBe(baseState)114 expect(nextState.anArray).not.toBe(baseState.anArray)114115 it("should support changing arrays - 2", () => {116 const nextState = immer(baseState, s => {116 expect(nextState.anArray).toEqual([3, "a", "b", {c: 3}, 1])117 })117 s.anArray.splice(1, 1, "a", "b")118 })119 expect(nextState).not.toBe(baseState)120 expect(nextState.anArray).not.toBe(baseState.anArray)121119 it("should support sorting arrays", () => {120 const nextState = immer(baseState, s => {121 s.anArray[2].c = 4122 s.anArray.sort()123 s.anArray[3].c = 5122 expect(nextState.anArray).toEqual([3, "a", "b", {c: 3}, 1])123 })125 expect(nextState).not.toBe(baseState)126 expect(nextState.anArray).not.toBe(baseState.anArray)127 expect(nextState.anArray).toEqual([1, 2, 3, {c: 5}])128 })124130 it("should updating inside arrays", () => {131 const nextState = immer(baseState, s => {132 s.anArray[2].test = true125 it("should support sorting arrays", () => {126 const nextState = immer(baseState, s => {127 s.anArray[2].c = 4128 s.anArray.sort()129 s.anArray[3].c = 5130 })131 expect(nextState).not.toBe(baseState)132 expect(nextState.anArray).not.toBe(baseState.anArray)133 expect(nextState.anArray).toEqual([1, 2, 3, {c: 5}])134 })134 expect(nextState).not.toBe(baseState)135 expect(nextState.anArray).not.toBe(baseState.anArray)136 expect(nextState.anArray).toEqual([3, 2, {c: 3, test: true}, 1])137 })135139 it("reusing object should work", () => {140 const nextState = immer(baseState, s => {141 const obj = s.anObject142 delete s.anObject143 s.messy = obj136 it("should updating inside arrays", () => {137 const nextState = immer(baseState, s => {138 s.anArray[2].test = true139 })140 expect(nextState).not.toBe(baseState)141 expect(nextState.anArray).not.toBe(baseState.anArray)142 expect(nextState.anArray).toEqual([3, 2, {c: 3, test: true}, 1])143 })145 expect(nextState).not.toBe(baseState)146 expect(nextState.anArray).toBe(baseState.anArray)147 expect(nextState).toEqual({148 anArray: [3, 2, {c: 3}, 1],149 aProp: "hi",150 messy: {151 nested: {152 yummie: true153 },154 coffee: false155 }156 })157 expect(nextState.messy.nested).toBe(baseState.anObject.nested)158 })144160 it("refs should be transparent", () => {161 const nextState = immer(baseState, s => {162 const obj = s.anObject163 s.aProp = "hello"164 delete s.anObject165 obj.coffee = true166 s.messy = obj145 it("reusing object should work", () => {146 const nextState = immer(baseState, s => {147 const obj = s.anObject148 delete s.anObject149 s.messy = obj150 })151 expect(nextState).not.toBe(baseState)152 expect(nextState.anArray).toBe(baseState.anArray)153 expect(nextState).toEqual({154 anArray: [3, 2, {c: 3}, 1],155 aProp: "hi",156 messy: {157 nested: {158 yummie: true159 },160 coffee: false161 }162 })163 expect(nextState.messy.nested).toBe(baseState.anObject.nested)164 })168 expect(nextState).not.toBe(baseState)169 expect(nextState.anArray).toBe(baseState.anArray)170 expect(nextState).toEqual({171 anArray: [3, 2, {c: 3}, 1],172 aProp: "hello",173 messy: {174 nested: {175 yummie: true176 },177 coffee: true178 }179 })180 expect(nextState.messy.nested).toBe(baseState.anObject.nested)181 })165183 it("should allow setting to undefined a defined draft property", () => {184 const nextState = immer(baseState, s => {185 s.aProp = undefined166 it("refs should be transparent", () => {167 const nextState = immer(baseState, s => {168 const obj = s.anObject169 s.aProp = "hello"170 delete s.anObject171 obj.coffee = true172 s.messy = obj173 })174 expect(nextState).not.toBe(baseState)175 expect(nextState.anArray).toBe(baseState.anArray)176 expect(nextState).toEqual({177 anArray: [3, 2, {c: 3}, 1],178 aProp: "hello",179 messy: {180 nested: {181 yummie: true182 },183 coffee: true184 }185 })186 expect(nextState.messy.nested).toBe(baseState.anObject.nested)187 })187 expect(nextState).not.toBe(baseState)188 expect(baseState.aProp).toBe("hi")189 expect(nextState.aProp).toBe(undefined)190 })188192 it("should revoke the proxy of the baseState after immer function is executed", () => {193 let proxy194 const nextState = immer(baseState, s => {195 proxy = s196 s.aProp = "hello"189 it("should allow setting to undefined a defined draft property", () => {190 const nextState = immer(baseState, s => {191 s.aProp = undefined192 })193 expect(nextState).not.toBe(baseState)194 expect(baseState.aProp).toBe("hi")195 expect(nextState.aProp).toBe(undefined)196 })198 expect(nextState).not.toBe(baseState)199 expect(baseState.aProp).toBe("hi")200 expect(nextState.aProp).toBe("hello")197202 expect(() => {203 proxy.aProp = "Hallo"204 }).toThrowError(/^Cannot perform.*on a proxy that has been revoked/)205 expect(() => {206 const aProp = proxy.aProp207 }).toThrowError(/^Cannot perform.*on a proxy that has been revoked/)198 // ES implementation does't protect against all outside modifications, just some..199 if (name === "proxy") {200 it("should revoke the proxy of the baseState after immer function is executed", () => {201 let proxy202 const nextState = immer(baseState, s => {203 proxy = s204 s.aProp = "hello"205 })206 expect(nextState).not.toBe(baseState)207 expect(baseState.aProp).toBe("hi")208 expect(nextState.aProp).toBe("hello")209209 expect(nextState).not.toBe(baseState)210 expect(baseState.aProp).toBe("hi")211 expect(nextState.aProp).toBe("hello")212 })210 expect(() => {211 proxy.aProp = "Hallo"212 }).toThrowError(/revoked/)213 expect(() => {214 const aProp = proxy.aProp215 }).toThrowError(/revoked/)216217 expect(nextState).not.toBe(baseState)218 expect(baseState.aProp).toBe("hi")219 expect(nextState.aProp).toBe("hello")220 })221 }222214 it("should revoke the proxy of the baseState after immer function is executed - 2", () => {215 let proxy216 const nextState = immer(baseState, s => {217 proxy = s.anObject223 it("should revoke the proxy of the baseState after immer function is executed - 2", () => {224 let proxy225 const nextState = immer(baseState, s => {226 proxy = s.anObject227 })228 expect(nextState).toBe(baseState)229 expect(() => {230 // In ES5 implemenation only protects existing props, but alas..231 proxy.coffee = "Hallo"232 }).toThrowError(/revoked/)233 expect(() => {234 const test = proxy.coffee235 }).toThrowError(/revoked/)236 })219 expect(nextState).toBe(baseState)220 expect(() => {221 proxy.test = "Hallo"222 }).toThrowError(/^Cannot perform.*on a proxy that has been revoked/)223 expect(() => {224 const test = proxy.test225 }).toThrowError(/^Cannot perform.*on a proxy that has been revoked/)226 })237228 afterEach(() => {229 expect(baseState).toBe(origBaseState)230 expect(baseState).toEqual(createBaseState())231 })238 afterEach(() => {239 expect(baseState).toBe(origBaseState)240 expect(baseState).toEqual(createBaseState())241 })242233 function createBaseState() {234 return {235 anArray: [3, 2, {c: 3}, 1],236 aProp: "hi",237 anObject: {238 nested: {239 yummie: true240 },241 coffee: false243 function createBaseState() {244 return {245 anArray: [3, 2, {c: 3}, 1],246 aProp: "hi",247 anObject: {248 nested: {249 yummie: true250 },251 coffee: false252 }253 }254 }244 }245})255 })256}
modified:__tests__/performance.js+28 added-8 removed
modified:changelog.md+4 added
added:es5.js+259 added
1"use strict"2// @ts-check34const PROXY_TARGET = Symbol("immer-proxy")5const CHANGED_STATE = Symbol("immer-changed-state")6const PARENT = Symbol("immer-parent")78let autoFreeze = true910/**11 * Immer takes a state, and runs a function against it.12 * That function can freely mutate the state, as it will create copies-on-write.13 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned14 *15 * @export16 * @param {any} baseState - the state to start with17 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified18 * @returns {any} a new state, or the base state if nothing was modified19 */20function immer(baseState, thunk) {21 let finalizing = false22 let finished = false23 const descriptors = {}24 const proxies = []2526 // creates a proxy for plain objects / arrays27 function createProxy(base, parent) {28 let proxy29 if (isPlainObject(base)) proxy = createObjectProxy(base)30 else if (Array.isArray(base)) proxy = createArrayProxy(base)31 else throw new Error("Expected a plain object or array")32 createHiddenProperty(proxy, PROXY_TARGET, base)33 createHiddenProperty(proxy, CHANGED_STATE, false)34 createHiddenProperty(proxy, PARENT, parent)35 proxies.push(proxy)36 return proxy37 }3839 function assertUnfinished() {40 if (finished)41 throw new Error(42 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"43 )44 }4546 function proxySet(proxy, prop, value) {47 // immer func not ended?48 assertUnfinished()49 // actually a change?50 if (Object.is(proxy[prop], value)) return51 // mark changed52 markDirty(proxy)53 // and stop proxying, we know this object has changed54 Object.defineProperty(proxy, prop, {55 enumerable: true,56 writable: true,57 configurable: true,58 value: value59 })60 }6162 function createPropertyProxy(prop) {63 return (64 descriptors[prop] ||65 (descriptors[prop] = {66 configurable: true,67 enumerable: true,68 get() {69 assertUnfinished()70 // find the target object71 const target = this[PROXY_TARGET]72 // find the original value73 const value = target[prop]74 // if we are finalizing, don't bother creating proxies, just return base value75 if (finalizing) return value76 // if not proxy-able, return value77 if (!isPlainObject(value) && !Array.isArray(value))78 return value79 // otherwise, create proxy80 const proxy = createProxy(value, this)81 // and make sure this proxy is returned from this prop in the future if read82 // (write behavior as is)83 Object.defineProperty(this, prop, {84 configurable: true,85 enumerable: true,86 get() {87 return proxy88 },89 set(value) {90 proxySet(this, prop, value)91 }92 })93 return proxy94 },95 set(value) {96 proxySet(this, prop, value)97 }98 })99 )100 }101102 function createObjectProxy(base) {103 const proxy = {}104 Object.keys(base).forEach(prop =>105 Object.defineProperty(proxy, prop, createPropertyProxy(prop))106 )107 return proxy108 }109110 function createArrayProxy(base) {111 const proxy = []112 for (let i = 0; i < base.length; i++)113 Object.defineProperty(proxy, "" + i, createPropertyProxy("" + i))114 return proxy115 }116117 // this sounds very expensive, but actually it is not that extensive in practice118 // as it will only visit proxies, and only do key-based change detection for objects for119 // which it is not already know that they are changed (that is, only object for which no known key was changed)120 function markChanges() {121 // intentionally we process the proxies in reverse order;122 // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore123 // reverse order of proxy creation approximates this124 for (let i = proxies.length - 1; i >= 0; i--) {125 const proxy = proxies[i]126 if (127 proxy[CHANGED_STATE] === false &&128 ((isPlainObject(proxy) && hasObjectChanges(proxy)) ||129 (Array.isArray(proxy) && hasArrayChanges(proxy)))130 ) {131 markDirty(proxy)132 }133 }134 }135136 function hasObjectChanges(proxy) {137 const baseKeys = Object.keys(proxy[PROXY_TARGET])138 const keys = Object.keys(proxy)139 return !shallowEqual(baseKeys, keys)140 }141142 function hasArrayChanges(proxy) {143 return proxy[PROXY_TARGET].length !== proxy.length144 }145146 function finalize(proxy) {147 // given a base object, returns it if unmodified, or return the changed cloned if modified148 if (!isProxy(proxy)) return proxy149 if (!proxy[CHANGED_STATE]) return proxy[PROXY_TARGET] // return the original target150 if (isPlainObject(proxy)) return finalizeObject(proxy)151 if (Array.isArray(proxy)) return finalizeArray(proxy)152 throw new Error("Illegal state")153 }154155 function finalizeObject(proxy) {156 const res = {}157 Object.keys(proxy).forEach(prop => {158 res[prop] = finalize(proxy[prop])159 })160 return freeze(res)161 }162163 function finalizeArray(proxy) {164 return freeze(proxy.map(finalize))165 }166167 // create proxy for root168 const rootClone = createProxy(baseState, undefined)169 // execute the thunk170 const maybeVoidReturn = thunk(rootClone)171 //values either than undefined will trigger warning;172 !Object.is(maybeVoidReturn, undefined) &&173 console.warn(174 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`175 )176 // and finalize the modified proxy177 finalizing = true178 // find and mark all changes (for parts not done yet)179 markChanges()180 const res = finalize(rootClone)181 // make sure all proxies become unusable182 finished = true183 return res184}185186function markDirty(proxy) {187 proxy[CHANGED_STATE] = true188 let parent = proxy189 while ((parent = parent[PARENT])) {190 if (parent[CHANGED_STATE] === true) return191 parent[CHANGED_STATE] = true192 }193}194195function isPlainObject(value) {196 if (value === null || typeof value !== "object") return false197 const proto = Object.getPrototypeOf(value)198 return proto === Object.prototype || proto === null199}200201function isProxy(value) {202 return !!(value && value[PROXY_TARGET])203}204205function freeze(value) {206 if (autoFreeze) {207 Object.freeze(value)208 }209 return value210}211212function createHiddenProperty(target, prop, value) {213 Object.defineProperty(target, prop, {214 value: value,215 enumerable: false,216 writable: true217 })218}219220function shallowEqual(objA, objB) {221 //From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js222 if (Object.is(objA, objB)) return true223 if (224 typeof objA !== "object" ||225 objA === null ||226 typeof objB !== "object" ||227 objB === null228 ) {229 return false230 }231 const keysA = Object.keys(objA)232 const keysB = Object.keys(objB)233 if (keysA.length !== keysB.length) return false234 for (let i = 0; i < keysA.length; i++) {235 if (236 !hasOwnProperty.call(objB, keysA[i]) ||237 !Object.is(objA[keysA[i]], objB[keysA[i]])238 ) {239 return false240 }241 }242 return true243}244245/**246 * Automatically freezes any state trees generated by immer.247 * This protects against accidental modifications of the state tree outside of an immer function.248 * This comes with a performance impact, so it is recommended to disable this option in production.249 * It is by default enabled.250 *251 * @returns {void}252 */253function setAutoFreeze(enableAutoFreeze) {254 autoFreeze = enableAutoFreeze255}256257createHiddenProperty(exports, "__esModule", true)258module.exports.default = immer259module.exports.setAutoFreeze = setAutoFreeze
modified:immer.js+5 added
1"use strict"2// @ts-check34if (typeof Proxy === "undefined")5 throw new Error(6 "Immer requires `Proxy` to be available, but it seems to be not available on your platform. Consider requiring immer '\"immer/es5\"' instead."7 )89/**10 * @typedef {Object} RevocableProxy11 * @property {any} proxy12 * @property {Function} revoke
220 unmodified lines
modified:package.json+3 added-2 removed
modified:readme.md+99 added-9 removed
19 unmodified lines
20Using 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).2122A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applicable to plain, native JavaScript data structures (arrays and objects) without further needing any library.2324## Installation2526`npm install immer`2728## API2930The immer package exposes a single function:31
1 unmodified line
3334## Example3536```javascript37import immer from "immer"3839const baseState = [40 {41 todo: "Learn typescript",42 done: true
27 unmodified lines
70// changed data not (dûh)71expect(nextState[1]).not.toBe(baseState[1])72```7374## Using immer on older JavaScript environments7576By default `immer` tries to use proxies for optimal performance.77However, on older JavaScript engines `Proxy` is not available.78For example, Microsoft Internet Explorer or React Native on Android.79In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:8081```javascript82import immer from "immer/es5"83```8485## Benefits8687* Use the language© to construct create your next state88* Use JavaScript native arrays and object89* Automatic immutability; any state tree produced by `immer` will by defualt be deeply frozen90* Strongly typed, no string based paths etc91* Deep updates are trivial92* Small, dependency free library with minimal api surface93* No accidental mutations of current state, but intentional mutations of a draft state
8 unmodified lines
102 Use `setAutoFreeze(true / false)` to turn this feature on or off.103104## Reducer Example10587A lot of words; here is a simple example of the difference that this approach could make in practice.106Here is a simple example of the difference that this approach could make in practice.107The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)108109_Note, this is just a sample application of the `immer` package. Immer is not just designed to simplify Redux reducers. It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing)_110
62 unmodified lines
173```174175Creating middleware or a reducer wrapper that applies `immer` automatically is left as exercise for the reader :-).176177---178179Here 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.180These examples are semantically equivalent and produce the exact same state.181182```javascript183// Plain reducer184function insertItem(array, action) {185 return [186 ...array.slice(0, action.index),187 action.item,188 ...array.slice(action.index)189 ]190}191192// With immer193function insertItem(array, action) {194 return immer(array, draft => {195 draft.splice(action.index, 0, action.item)196 })197}198199// Plain reducer200function removeItem(array, action) {201 return [202 ...array.slice(0, action.index),203 ...array.slice(action.index + 1)204 ];205}206207// With immer208function removeItem(array, action) {209 return immer(array, draft => {210 draft.splice(action.index, 1)211 })212}213214// Plain reducer215function updateObjectInArray(array, action) {216 return array.map( (item, index) => {217 if(index !== action.index) {218 // This isn't the item we care about - keep it as-is219 return item;220 }221222 // Otherwise, this is the one we want - return an updated value223 return {224 ...item,225 ...action.item226 };227 });228}229230// With immer231function updateObjectInArray(array, action) {232 return immer(array, draft => {233 draft[action.index] = { ...item, ...action.item}234 // Alternatively, since arbitrarily deep updates are supported:235 // Object.assign(draft[action.index], action.item)236 })237}238```239240## Performance241242Here is a [simple benchmark](__tests__/performance.js) on the performance of `immer`.243This test takes 100.000 todo items, and updates 10.000 of them.244These tests were executed on Node 8.4.0245246```165 performance166 ✓ just mutate (1ms) // No immutability at all167 ✓ deepclone, then mutate (647ms) // Clone entire tree, then mutate (no structural sharing!)168 ✓ handcrafted reducer (17ms) // Implement it as typical Redux reducer, with slices and spread operator169 ✓ immutableJS (81ms) // Use immutableJS and leverage `withMutations` for best performance170 ✓ immer - with autofreeze (309ms) // Immer, with auto freeze enabled171 ✓ immer - without autofreeze (148ms) // Immer, but without auto freeze enabled247 ✓ just mutate (2ms)248 (No immutability at all)249 ✓ deepclone, then mutate (390ms)250 (Clone entire tree, then mutate (no structural sharing!))251 ✓ handcrafted reducer (27ms)252 (Implement it as typical Redux reducer, with slices and spread operator)253 ✓ immutableJS (68ms)254 (Use immutableJS and leverage `withMutations` for best performance)255 ✓ immer (proxy) - with autofreeze (303ms)256 (Immer, with auto freeze enabled, default implementation)257 ✓ immer (proxy) - without autofreeze (142ms)258 (Immer, with auto freeze disabled, default implementation)259 ✓ immer (es5) - with autofreeze (414ms)260 (Immer, with auto freeze enabled, compatibility implementation)261 ✓ immer (es5) - without autofreeze (341ms)262 (Immer, with auto freeze disabled, default implementation)263```264265## Limitations266176* This package requires Proxies, so Safari > 9, no Internet Explorer, no React Native on Android. This can potentially done, so feel free to upvote on [#8](https://github.com/mweststrate/immer/issues/8) if you need this :)267* Currently, only tree shaped states are supported. Cycles could potentially be supported as well (PR's welcome)268* Currently, only supports plain objects and arrays. Non-plain data structures (like `Map`, `Set`) not (yet). (PR's welcome)269270## Pitfalls:
7 unmodified lines