Skip to content
Myr

Merge branch 'master' into travis

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

authored by Michel Weststrate · committed by GitHub · parents 6b47142, 9c89d5a · Browse files · 14 files+645 added−432 removed
This commit

State

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

Diff stats

14 files+645 added−432 removed

  • tests:+173 added−170 removed
  • other:+472 added−262 removed

14 files+645 added−432 removed

added:__performance_tests__/todo.js+181 added
1"use strict"2import immerProxy, {setAutoFreeze as setAutoFreezeProxy} from ".."3import immerEs5, {setAutoFreeze as setAutoFreezeEs5} from "../es5"4import cloneDeep from "lodash.clonedeep"5import {List, Record} from "immutable"6import deepFreeze from "deep-freeze"78function freeze(x) {9 Object.freeze(x)10 return x11}1213describe("performance", () => {14 const MAX = 10000015 const MODIFY_FACTOR = 0.116 const baseState = []17 let frozenBazeState18 let immutableJsBaseState1920 // produce the base state21 for (let i = 0; i < MAX; i++) {22 baseState.push({23 todo: "todo_" + i,24 done: false,25 someThingCompletelyIrrelevant: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]26 })27 }2829 // Produce the frozen bazeState30 frozenBazeState = deepFreeze(cloneDeep(baseState))3132 // generate immutalbeJS base state33 const todoRecord = Record({34 todo: "",35 done: false,36 someThingCompletelyIrrelevant: []37 })38 immutableJsBaseState = List(baseState.map(todo => todoRecord(todo)))3940 function measure(name, fn) {41 global.gc && global.gc()42 test(name, fn)43 }4445 {46 const draft = cloneDeep(baseState)47 measure("just mutate", () => {48 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {49 draft[i].done = true50 }51 })52 }5354 {55 const draft = cloneDeep(baseState)56 measure("just mutate, freeze", () => {57 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {58 draft[i].done = true59 }60 deepFreeze(draft)61 })62 }6364 measure("deepclone, then mutate", () => {65 const draft = cloneDeep(baseState)66 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {67 draft[i].done = true68 }69 })7071 measure("deepclone, then mutate, then freeze", () => {72 const draft = cloneDeep(baseState)73 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {74 draft[i].done = true75 }76 deepFreeze(draft)77 })7879 measure("handcrafted reducer (no freeze)", () => {80 const nextState = [81 ...baseState.slice(0, MAX * MODIFY_FACTOR).map(todo => ({82 ...todo,83 done: true84 })),85 ...baseState.slice(MAX * MODIFY_FACTOR)86 ]87 })8889 measure("handcrafted reducer (with freeze)", () => {90 const nextState = freeze([91 ...baseState.slice(0, MAX * MODIFY_FACTOR).map(todo =>92 freeze({93 ...todo,94 done: true95 })96 ),97 ...baseState.slice(MAX * MODIFY_FACTOR)98 ])99 })100101 measure("naive handcrafted reducer (without freeze)", () => {102 const nextState = baseState.map((todo, index) => {103 if (index < MAX * MODIFY_FACTOR)104 return {105 ...todo,106 done: true107 }108 else return todo109 })110 })111112 measure("naive handcrafted reducer (with freeze)", () => {113 const nextState = deepFreeze(114 baseState.map((todo, index) => {115 if (index < MAX * MODIFY_FACTOR)116 return {117 ...todo,118 done: true119 }120 else return todo121 })122 )123 })124125 measure("immutableJS", () => {126 let state = immutableJsBaseState127 state.withMutations(state => {128 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {129 state.setIn([i, "done"], true)130 }131 })132 })133134 measure("immutableJS + toJS", () => {135 let state = immutableJsBaseState136 .withMutations(state => {137 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {138 state.setIn([i, "done"], true)139 }140 })141 .toJS()142 })143144 measure("immer (proxy) - without autofreeze", () => {145 setAutoFreezeProxy(false)146 immerProxy(baseState, draft => {147 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {148 draft[i].done = true149 }150 })151 setAutoFreezeProxy(true)152 })153154 measure("immer (proxy) - with autofreeze", () => {155 setAutoFreezeProxy(true)156 immerProxy(frozenBazeState, draft => {157 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {158 draft[i].done = true159 }160 })161 })162163 measure("immer (es5) - without autofreeze", () => {164 setAutoFreezeEs5(false)165 immerEs5(baseState, draft => {166 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {167 draft[i].done = true168 }169 })170 setAutoFreezeEs5(true)171 })172173 measure("immer (es5) - with autofreeze", () => {174 setAutoFreezeEs5(true)175 immerEs5(frozenBazeState, draft => {176 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {177 draft[i].done = true178 }179 })180 })181})
modified:__tests__/base.js+126 added-19 removed
1"use strict"2import immerProxy from ".."3import immerEs5 from "../es5"2import * as immerProxy from ".."3import * as immerEs5 from "../es5"4import deepFreeze from "deep-freeze"55runBaseTest("proxy", immerProxy)6runBaseTest("es5", immerEs5)6runBaseTest("proxy (no freeze)", immerProxy, false)7runBaseTest("proxy (autofreeze)", immerProxy, true)8runBaseTest("es5 (no freeze)", immerEs5, false)9runBaseTest("es5 (autofreeze)", immerEs5, true)108function runBaseTest(name, immer) {11function runBaseTest(name, lib, freeze) {12 describe(`base functionality - ${name}`, () => {13 const immer = lib.default14 let baseState15 let origBaseState1617 beforeEach(() => {18 lib.setAutoFreeze(freeze)19 origBaseState = baseState = createBaseState()20 })2122 it("should return the original without modifications", () => {
30 unmodified lines
53 // structural sharing?54 expect(nextState.nested).toBe(baseState.nested)55 })5652 it("deep change bubbles up", () => {53 const nextState = immer(baseState, s => {54 s.anObject.nested.yummie = false57 if (58 ("should preserve type",59 () => {60 const nextState = immer(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"65 expect(Array.isArray(s)).toBe(true)66 expect(s.protoType).toBe(Object)67 })68 expect(Array.isArray(nextState)).toBe(true)69 expect(nextState.protoType).toBe(Object)70 })71 )72 it("deep change bubbles up", () => {73 const nextState = immer(baseState, s => {74 s.anObject.nested.yummie = false75 })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 })76 expect(nextState).not.toBe(baseState)77 expect(nextState.anObject).not.toBe(baseState.anObject)78 expect(baseState.anObject.nested.yummie).toBe(true)79 expect(nextState.anObject.nested.yummie).toBe(false)80 expect(nextState.anArray).toBe(baseState.anArray)81 })8283 it("can add props", () => {84 const nextState = immer(baseState, s => {85 s.anObject.cookie = {tasty: true}
52 unmodified lines
138 })139 expect(nextState).not.toBe(baseState)140 expect(nextState.anArray).not.toBe(baseState.anArray)141122 expect(nextState.anArray).toEqual([3, "a", "b", {c: 3}, 1])142 expect(enumerableOnly(nextState.anArray)).toEqual([143 3,144 "a",145 "b",146 {c: 3},147 1148 ])149 })150151 it("can delete array items", () => {152 const nextState = immer(baseState, s => {153 s.anArray.length = 3154 })155 expect(nextState).not.toBe(baseState)156 expect(nextState.anObject).toBe(baseState.anObject)157 expect(nextState.anArray).not.toBe(baseState.anArray)158 expect(nextState.anArray).toEqual([3, 2, {c: 3}])159 })160161 it("should support sorting arrays", () => {162 const nextState = immer(baseState, s => {163 s.anArray[2].c = 4164 s.anArray.sort()165 s.anArray[3].c = 5166 })167 expect(nextState).not.toBe(baseState)168 expect(nextState.anArray).not.toBe(baseState.anArray)133 expect(nextState.anArray).toEqual([1, 2, 3, {c: 5}])169 expect(enumerableOnly(nextState.anArray)).toEqual([1, 2, 3, {c: 5}])170 })171172 it("should expose property descriptors", () => {173 const nextState = immer([], s => {174 expect(Object.getOwnPropertyDescriptor(s, 0)).toBe(undefined)175 s.unshift("x")176 expect(Object.getOwnPropertyDescriptor(s, 0)).toEqual({177 configurable: true,178 enumerable: true,179 value: "x",180 writable: true181 })182 expect(s.length).toBe(1)183 expect(s[0] === "x").toBe(true)184 })185 expect(nextState).toEqual(["x"])186 expect(Object.getOwnPropertyDescriptor(nextState, 0)).toEqual({187 configurable: !freeze,188 enumerable: true,189 value: "x",190 writable: !freeze191 })192 })193194 it("should support sorting arrays - 2", () => {195 const nextState = immer(baseState, s => {196 s.anArray.unshift("x")197 s.anArray[3].c = 4198 s.anArray.sort()199 s.anArray[3].c = 5200 s.anArray.unshift("y")201 })202 expect(nextState).not.toBe(baseState)203 expect(nextState.anArray).not.toBe(baseState.anArray)204 expect(enumerableOnly(nextState.anArray)).toEqual([205 "y",206 1,207 2,208 3,209 {c: 5},210 "x"211 ])212 })213214 it("should updating inside arrays", () => {215 const nextState = immer(baseState, s => {216 s.anArray[2].test = true217 })
9 unmodified lines
227 s.messy = obj228 })229 expect(nextState).not.toBe(baseState)230 expect(nextState.anArray).toBe(baseState.anArray)153 expect(nextState).toEqual({231 expect(enumerableOnly(nextState)).toEqual({232 anArray: [3, 2, {c: 3}, 1],233 aProp: "hi",234 messy: {235 nested: {
11 unmodified lines
247 s.aProp = "hello"248 delete s.anObject249 obj.coffee = true250 s.messy = obj251 debugger252 })253 expect(nextState).not.toBe(baseState)254 expect(nextState.anArray).toBe(baseState.anArray)176 expect(nextState).toEqual({255 expect(enumerableOnly(nextState)).toEqual({256 anArray: [3, 2, {c: 3}, 1],257 aProp: "hello",258 messy: {259 nested: {
53 unmodified lines
313 const test = proxy.coffee314 }).toThrowError(/revoked/)315 })316317 it("should reflect all changes made in the draft immediately", () => {318 immer(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([323 "test",324 5,325 2,326 {c: 3},327 1328 ])329 draft.stuffz = "coffee"330 expect(draft.stuffz).toBe("coffee")331 })332 })333334 afterEach(() => {335 expect(baseState).toBe(origBaseState)336 expect(baseState).toEqual(createBaseState())337 })338339 function createBaseState() {244 return {340 const data = {341 anArray: [3, 2, {c: 3}, 1],342 aProp: "hi",343 anObject: {344 nested: {
1 unmodified line
346 },347 coffee: false348 }349 }350 return freeze ? deepFreeze(data) : data351 }352 })353}354355function enumerableOnly(x) {356 // this can be done better...357 return JSON.parse(JSON.stringify(x))358}359360// TODO: test problem scenarios361// nesting immmer362// non-trees363// complex objects / functions
modified:__tests__/frozen.js+47 added-39 removed
deleted:__tests__/performance.js-112 removed
1"use strict"2import immerProxy, {setAutoFreeze as setAutoFreezeProxy} from ".."3import immerEs5, {setAutoFreeze as setAutoFreezeEs5} from "../es5"4import cloneDeep from "lodash.clonedeep"5import {List, Record} from "immutable"67describe("performance", () => {8 const MAX = 1000009 const MODIFY_FACTOR = 0.110 const baseState = []11 let frozenBazeState12 let immutableJsBaseState1314 // produce the base state15 for (let i = 0; i < MAX; i++) {16 baseState.push({17 todo: "todo_" + i,18 done: false,19 someThingCompletelyIrrelevant: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]20 })21 }2223 // Produce the frozen bazeState24 frozenBazeState = baseState.map(todo => {25 const newTodo = {...todo}26 newTodo.someThingCompletelyIrrelevant = todo.someThingCompletelyIrrelevant.slice()27 Object.freeze(newTodo.someThingCompletelyIrrelevant)28 Object.freeze(newTodo)29 return newTodo30 })31 Object.freeze(frozenBazeState)3233 // generate immutalbeJS base state34 const todoRecord = Record({35 todo: "",36 done: false,37 someThingCompletelyIrrelevant: []38 })39 immutableJsBaseState = List(baseState.map(todo => todoRecord(todo)))4041 // The benchmarks4243 test("just mutate", () => {44 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {45 baseState[i].done = true46 }47 })4849 test("deepclone, then mutate", () => {50 const draft = cloneDeep(baseState)51 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {52 draft[i].done = true53 }54 })5556 test("handcrafted reducer", () => {57 const nextState = [58 ...baseState.slice(0, MAX * MODIFY_FACTOR).map(todo => ({59 ...todo,60 done: true61 })),62 ...baseState.slice(MAX * MODIFY_FACTOR)63 ]64 })6566 test("immutableJS", () => {67 let state = immutableJsBaseState68 state.withMutations(state => {69 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {70 state.setIn([i, "done"], true)71 }72 })73 })7475 test("immer (proxy) - with autofreeze", () => {76 setAutoFreezeProxy(true)77 immerProxy(frozenBazeState, draft => {78 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {79 draft[i].done = true80 }81 })82 })8384 test("immer (proxy) - without autofreeze", () => {85 setAutoFreezeProxy(false)86 immerProxy(baseState, draft => {87 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {88 draft[i].done = true89 }90 })91 setAutoFreezeProxy(true)92 })9394 test("immer (es5) - with autofreeze", () => {95 setAutoFreezeEs5(true)96 immerEs5(frozenBazeState, draft => {97 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {98 draft[i].done = true99 }100 })101 })102103 test("immer (es5) - without autofreeze", () => {104 setAutoFreezeEs5(false)105 immerEs5(baseState, draft => {106 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {107 draft[i].done = true108 }109 })110 setAutoFreezeEs5(true)111 })112})
added:images/immer.pngbinary

A binary file, added.

added:images/performance.pngbinary

A binary file, added.

modified:changelog.md+8 added
modified:es5.js+94 added-97 removed
1"use strict"2// @ts-check34const PROXY_TARGET = Symbol("immer-proxy")5const CHANGED_STATE = Symbol("immer-changed-state")6const PARENT = Symbol("immer-parent")4const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version56let autoFreeze = true78/**
9 unmodified lines
18function immer(baseState, thunk) {19 let finalizing = false20 let finished = false21 const descriptors = {}24 const proxies = []22 const states = []2324 class State {25 constructor(parent, proxy, base) {26 this.modified = false27 this.hasCopy = false28 this.parent = parent29 this.base = base30 this.proxy = proxy31 this.copy = undefined32 }3334 get source() {35 return this.hasCopy ? this.copy : this.base36 }3738 get(prop) {39 assertUnfinished()40 const value = this.source[prop]41 if (!finalizing && !isProxy(value) && isProxyable(value)) {42 this.prepareCopy()43 return (this.copy[prop] = createProxy(this, value))44 }45 return value46 }4748 set(prop, value) {49 assertUnfinished()50 if (!this.modified) {51 if (this.source[prop] === value) return52 this.markChanged()53 }54 this.prepareCopy()55 this.copy[prop] = value56 }5758 markChanged() {59 if (!this.modified) {60 this.modified = true61 if (this.parent) this.parent.markChanged()62 }63 }6465 prepareCopy() {66 if (this.hasCopy) return67 this.hasCopy = true68 this.copy = Array.isArray(this.base)69 ? this.base.slice()70 : Object.assign({}, this.base)71 }72 }7374 // creates a proxy for plain objects / arrays27 function createProxy(base, parent) {75 function createProxy(parent, base) {76 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)77 if (Array.isArray(base)) proxy = createArrayProxy(base)78 else proxy = createObjectProxy(base)79 const state = new State(parent, proxy, base)80 createHiddenProperty(proxy, PROXY_STATE, state)81 states.push(state)82 return proxy83 }8439 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 }6185 function createPropertyProxy(prop) {86 return (87 descriptors[prop] ||88 (descriptors[prop] = {89 configurable: true,90 enumerable: true,91 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 proxy92 return this[PROXY_STATE].get(prop)93 },94 set(value) {96 proxySet(this, prop, value)95 this[PROXY_STATE].set(prop, value)96 }97 })98 )99 }100101 function createObjectProxy(base) {103 const proxy = {}102 const proxy = Object.assign({}, base)103 Object.keys(base).forEach(prop =>104 Object.defineProperty(proxy, prop, createPropertyProxy(prop))105 )106 return proxy107 }108109 function createArrayProxy(base) {111 const proxy = []110 const proxy = new Array(base.length)111 for (let i = 0; i < base.length; i++)112 Object.defineProperty(proxy, "" + i, createPropertyProxy("" + i))113 return proxy114 }115116 function assertUnfinished() {117 if (finished)118 throw new Error(119 "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"120 )121 }122123 // this sounds very expensive, but actually it is not that extensive in practice124 // as it will only visit proxies, and only do key-based change detection for objects for125 // which it is not already know that they are changed (that is, only object for which no known key was changed)126 function markChanges() {127 // intentionally we process the proxies in reverse order;128 // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore129 // 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)130 for (let i = states.length - 1; i >= 0; i--) {131 const state = states[i]132 if (state.modified === false) {133 if (Array.isArray(state.base)) {134 if (hasArrayChanges(state)) state.markChanged()135 } else if (hasObjectChanges(state)) state.markChanged()136 }137 }138 }139136 function hasObjectChanges(proxy) {137 const baseKeys = Object.keys(proxy[PROXY_TARGET])138 const keys = Object.keys(proxy)140 function hasObjectChanges(state) {141 const baseKeys = Object.keys(state.base)142 const keys = Object.keys(state.proxy)143 return !shallowEqual(baseKeys, keys)144 }145142 function hasArrayChanges(proxy) {143 return proxy[PROXY_TARGET].length !== proxy.length146 function hasArrayChanges(state) {147 return state.proxy.length !== state.base.length148 }149150 function finalize(proxy) {151 // given a base object, returns it if unmodified, or return the changed cloned if modified152 if (!isProxy(proxy)) return proxy149 if (!proxy[CHANGED_STATE]) return proxy[PROXY_TARGET] // return the original target150 if (isPlainObject(proxy)) return finalizeObject(proxy)153 const state = proxy[PROXY_STATE]154 if (state.modified === false) return state.base // return the original target155 if (Array.isArray(proxy)) return finalizeArray(proxy)152 throw new Error("Illegal state")156 return finalizeObject(proxy)157 }158159 function finalizeObject(proxy) {156 const res = {}157 Object.keys(proxy).forEach(prop => {158 res[prop] = finalize(proxy[prop])160 const res = Object.assign({}, proxy)161 Object.keys(res).forEach(prop => {162 res[prop] = finalize(res[prop])163 })164 return freeze(res)165 }166
1 unmodified line
168 return freeze(proxy.map(finalize))169 }170171 // create proxy for root168 const rootClone = createProxy(baseState, undefined)172 const rootClone = createProxy(undefined, baseState)173 // execute the thunk174 const maybeVoidReturn = thunk(rootClone)175 //values either than undefined will trigger warning;176 !Object.is(maybeVoidReturn, undefined) &&
9 unmodified lines
186 finished = true187 return res188}189186function 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 }190function isProxy(value) {191 return !!value && !!value[PROXY_STATE]192}193195function isPlainObject(value) {196 if (value === null || typeof value !== "object") return false194function isProxyable(value) {195 if (!value) return false196 if (typeof value !== "object") return false197 if (Array.isArray(value)) return true198 const proto = Object.getPrototypeOf(value)198 return proto === Object.prototype || proto === null199 return (proto === proto) === null || Object.prototype200}201201function isProxy(value) {202 return !!(value && value[PROXY_TARGET])203}204202function freeze(value) {203 if (autoFreeze) {204 Object.freeze(value)205 }
51 unmodified lines
modified:immer.js+158 added-134 removed
4 unmodified lines
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} revoke13 */9const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version10let autoFreeze = true1115const IMMER_PROXY = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version12const objectTraps = {13 get(target, prop) {14 if (prop === PROXY_STATE) return target15 return target.get(prop)16 },17 has(target, prop) {18 return prop in target.source19 },20 ownKeys(target) {21 return Reflect.ownKeys(target.source)22 },23 set(target, prop, value) {24 target.set(prop, value)25 return true26 },27 deleteProperty(target, prop) {28 target.deleteProp(prop)29 return true30 },31 getOwnPropertyDescriptor(target, prop) {32 return target.getOwnPropertyDescriptor(prop)33 },34 defineProperty(target, property, descriptor) {35 target.defineProperty(property, descriptor)36 return true37 },38 setPrototypeOf() {39 throw new Error("Don't even try this...")40 }41}4217// This property indicates that the current object is cloned for another object,18// to make sure the proxy of a frozen object is writeable19const CLONE_TARGET = Symbol("immer-clone-target")43const arrayTraps = {44 get(target, prop) {45 if (prop === PROXY_STATE) return target[0]46 return target[0].get(prop)47 },48 has(target, prop) {49 return prop in target[0].source50 },51 ownKeys(target) {52 return Reflect.ownKeys(target[0].source)53 },54 set(target, prop, value) {55 target[0].set(prop, value)56 return true57 },58 deleteProperty(target, prop) {59 target[0].deleteProp(prop)60 return true61 },62 getOwnPropertyDescriptor(target, prop) {63 return target[0].getOwnPropertyDescriptor(prop)64 },65 defineProperty(target, property, descriptor) {66 target[0].defineProperty(property, descriptor)67 return true68 },69 setPrototypeOf() {70 throw new Error("Don't even try this...")71 }72}7321let autoFreeze = true2274/**75 * Immer takes a state, and runs a function against it.76 * That function can freely mutate the state, as it will create copies-on-write.77 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned
3 unmodified lines
81 * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified82 * @returns {any} a new state, or the base state if nothing was modified83 */84function immer(baseState, thunk) {34 /**35 * Maps baseState objects to revocable proxies36 * @type {Map<Object,RevocableProxy>}37 */38 const revocableProxies = new Map()85 const revocableProxies = []39 // Maps baseState objects to their copies8641 const copies = new Map()87 class State {88 constructor(parent, base) {89 this.modified = false90 this.parent = parent91 this.base = base92 this.copy = undefined93 this.proxies = {}94 }9543 const objectTraps = {44 get(target, prop) {45 if (prop === IMMER_PROXY) return target46 return createProxy(getCurrentSource(target)[prop])47 },48 has(target, prop) {49 return prop in getCurrentSource(target)50 },51 ownKeys(target) {52 return Reflect.ownKeys(getCurrentSource(target))53 },54 set(target, prop, value) {55 const current = createProxy(getCurrentSource(target)[prop])56 const newValue = createProxy(value)57 if (current !== newValue) {58 const copy = getOrCreateCopy(target)59 copy[prop] = isProxy(newValue)60 ? newValue[IMMER_PROXY]61 : newValue96 get source() {97 return this.modified === true ? this.copy : this.base98 }99100 get(prop) {101 if (this.modified) {102 const value = this.copy[prop]103 if (!isProxy(value) && isProxyable(value))104 return (this.copy[prop] = createProxy(this, value))105 return value106 } else {107 if (prop in this.proxies) return this.proxies[prop]108 const value = this.base[prop]109 if (!isProxy(value) && isProxyable(value))110 return (this.proxies[prop] = createProxy(this, value))111 return value112 }63 return true64 },65 deleteProperty(target, property) {66 const copy = getOrCreateCopy(target)67 delete copy[property]68 return true113 }70 }11472 // creates a copy for a base object if there ain't one73 function getOrCreateCopy(base) {74 let copy = copies.get(base)75 if (copy) return copy76 const cloneTarget = base[CLONE_TARGET]77 if (cloneTarget) {78 // base is a clone already (source was frozen), no need to create addtional copy79 copies.set(cloneTarget, base)80 return base115 set(prop, value) {116 if (!this.modified) {117 if (118 (prop in this.base && this.base[prop] === value) ||119 (prop in this.proxies && this.proxies[prop] === value)120 )121 return122 this.markChanged()123 }124 this.copy[prop] = value125 }82 // create a fresh copy83 copy = Array.isArray(base) ? base.slice() : Object.assign({}, base)84 copies.set(base, copy)85 return copy86 }12688 // returns the current source of truth for a base object89 function getCurrentSource(base) {90 const copy = copies.get(base)91 return copy || base92 }127 deleteProp(prop) {128 this.markChanged()129 delete this.copy[prop]130 }13194 // creates a proxy for plain objects / arrays95 function createProxy(base) {96 if (isPlainObject(base) || Array.isArray(base)) {97 if (isProxy(base)) return base // avoid double wrapping98 if (revocableProxies.has(base))99 return revocableProxies.get(base).proxy100 let proxyTarget101 // special case, if the base tree is frozen, we cannot modify it's proxy it in strict mode, clone first.102 if (Object.isFrozen(base)) {103 proxyTarget = Array.isArray(base)104 ? base.slice()105 : Object.assign({}, base)106 Object.defineProperty(proxyTarget, CLONE_TARGET, {107 enumerable: false,108 value: base,109 configurable: true110 })111 } else {112 proxyTarget = base132 getOwnPropertyDescriptor(prop) {133 const owner = this.modified134 ? this.copy135 : prop in this.proxies ? this.proxies : this.base136 const descriptor = Reflect.getOwnPropertyDescriptor(owner, prop)137 if (descriptor) descriptor.configurable = true // XXX: is this really needed?138 return descriptor139 }140141 defineProperty(property, descriptor) {142 this.markChanged()143 Object.defineProperty(this.copy, property, descriptor)144 }145146 markChanged() {147 if (!this.modified) {148 this.modified = true149 this.copy = Array.isArray(this.base) // TODO: eliminate those isArray checks?150 ? this.base.slice()151 : Object.assign({}, this.base)152 Object.assign(this.copy, this.proxies) // yup that works for arrays as well153 if (this.parent) this.parent.markChanged()154 }114 // create the proxy115 const revocableProxy = Proxy.revocable(proxyTarget, objectTraps)116 revocableProxies.set(base, revocableProxy)117 return revocableProxy.proxy155 }119 return base156 }157122 // checks if the given base object has modifications, either because it is modified, or123 // because one of it's children is124 function hasChanges(base) {125 const proxy = revocableProxies.get(base)126 if (!proxy) return false // nobody did read this object127 if (copies.has(base)) return true // a copy was created, so there are changes128 // look deeper129 const keys = Object.keys(base)130 for (let i = 0; i < keys.length; i++) {131 const value = base[keys[i]]132 if (133 (Array.isArray(value) || isPlainObject(value)) &&134 hasChanges(value)135 )136 return true158 // creates a proxy for plain objects / arrays159 function createProxy(parentState, base) {160 const state = new State(parentState, base)161 let proxy162 if (Array.isArray(base)) {163 // Proxy should be created with an array to make it an array for JS164 // so... here you have it!165 proxy = Proxy.revocable([state], arrayTraps)166 } else {167 proxy = Proxy.revocable(state, objectTraps)168 }138 return false169 revocableProxies.push(proxy)170 return proxy.proxy171 }172173 // given a base object, returns it if unmodified, or return the changed cloned if modified174 function finalize(base) {143 if (isPlainObject(base)) return finalizeObject(base)144 if (Array.isArray(base)) return finalizeArray(base)175 if (isProxy(base)) {176 const state = base[PROXY_STATE]177 if (state.modified === true) {178 if (Array.isArray(state.base)) return finalizeArray(state)179 return finalizeObject(state)180 } else return state.base181 }182 return base183 }184148 function finalizeObject(thing) {149 if (!hasChanges(thing)) return thing150 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..185 function finalizeObject(state) {186 const copy = state.copy187 Object.keys(copy).forEach(prop => {188 copy[prop] = finalize(copy[prop])189 })154 delete copy[CLONE_TARGET]190 return freeze(copy)191 }192158 function finalizeArray(thing) {159 if (!hasChanges(thing)) return thing160 const copy = getOrCreateCopy(thing) // TODO: getOrCreate is weird here..193 function finalizeArray(state) {194 const copy = state.copy195 copy.forEach((value, index) => {196 copy[index] = finalize(copy[index])197 })164 delete copy[CLONE_TARGET]198 return freeze(copy)199 }200201 // create proxy for root169 const rootClone = createProxy(baseState)202 const rootClone = createProxy(undefined, baseState)203 // execute the thunk204 const maybeVoidReturn = thunk(rootClone)205 //values either than undefined will trigger warning;206 !Object.is(maybeVoidReturn, undefined) &&207 console.warn(208 `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`209 )177 // console.log(`proxies: ${revocableProxies.size}, copies: ${copies.size}`)178 // revoke all proxies179 revoke(revocableProxies)210 // and finalize the modified proxy181 return finalize(baseState)211 const res = finalize(rootClone)212 // revoke all proxies213 revocableProxies.forEach(p => p.revoke())214 return res215}216184/**185 * Revoke all the proxies stored in the revocableProxies map186 *187 * @param {Map<Object,RevocableProxy>} revocableProxies188 */189function revoke(revocableProxies) {190 for (var revocableProxy of revocableProxies.values()) {191 revocableProxy.revoke()192 }217function isProxy(value) {218 return !!value && !!value[PROXY_STATE]219}220195function isPlainObject(value) {196 if (value === null || typeof value !== "object") return false221function isProxyable(value) {222 if (!value) return false223 if (typeof value !== "object") return false224 if (Array.isArray(value)) return true225 const proto = Object.getPrototypeOf(value)198 return proto === Object.prototype || proto === null226 return (proto === proto) === null || Object.prototype227}228201function isProxy(value) {202 return !!value && !!value[IMMER_PROXY]203}204229function freeze(value) {230 // short circuit to achieve 100% code coverage instead of 98%231 /*232 if(autoFreeze) {
24 unmodified lines
deleted:immer.pngbinary

A binary file, deleted.

modified:index.d.ts+1 added-1 removed
modified:package.json+6 added-4 removed
modified:readme.md+20 added-26 removed
13 unmodified lines
14The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_.15Once all your mutations are completed, immer will produce the _nextState_ based on the mutations to the draft state.16This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.1718![immer.png](immer.png)18![immer.png](images/immer.png)1920Using 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.
213 unmodified lines
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```247 ✓ 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```264240## Limitations241242* Currently, only tree shaped states are supported. Cycles could potentially be supported as well (PR's welcome)243* Currently, only supports plain objects and arrays. Non-plain data structures (like `Map`, `Set`) not (yet). (PR's welcome)
2 unmodified lines
246247* Make sure to modify the draft state you get passed in in the callback function, not the original current state that was passed as the first argument to `immer`!248* Since immer uses proxies, reading huge amounts of data from state comes with an overhead. If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the `immer` block or read from the `currentState` rather than the `draftState`249250## Performance251252Here is a [simple benchmark](__tests__/performance.js) on the performance of `immer`.253This test takes 100.000 todo items, and updates 10.000 of them.254_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.255256These tests were executed on Node 8.4.0.257Use `yarn test:perf` to reproduce them locally.258259![immer.png](images/immer.png)260261Some observations:262* 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).263* 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.264* Immer with proxies is roughly speaking twice as slow as a hand written reducer. This is in practice negclectable.265* 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)266* 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.267* 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.268269## Credits270271Special thanks goes to @Mendix, which supports it's employees to experiment completely freely two full days a month, which formed the kick-start for this project.
modified:yarn.lock+4 added
923 unmodified lines
924deep-extend@~0.4.0:925 version "0.4.2"926 resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.4.2.tgz#48b699c27e334bf89f10892be432f6e4c7d34a7f"927928deep-freeze@^0.0.1:929 version "0.0.1"930 resolved "https://registry.yarnpkg.com/deep-freeze/-/deep-freeze-0.0.1.tgz#3a0b0005de18672819dfd38cd31f91179c893e84"931932deep-is@~0.1.3:933 version "0.1.3"934 resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34"935
2186 unmodified lines