Cleanup, run tests on both implementations
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 · parent aaa77bd · Browse files · 7 files·+539 added−479 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+539 added−479 removed
- tests:+237 added−210 removed
- other:+302 added−269 removed
Provenance
- Commit
2399cb2- Tree
bca6f5d- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
aaa77bd
7 files changed+539 added−479 removed
modified:__tests__/base.js+209 added-202 removed
1 "use strict"2-import immer from ".."2+import immerProxy from ".."3+import immerEs5 from "../es5"4 4-describe("base", () => {5- let baseState6- let origBaseState5+runBaseTest("proxy", immerProxy)6+runBaseTest("es5", immerEs5)7 8- beforeEach(() => {9- origBaseState = baseState = createBaseState()10- })8+function runBaseTest(name, immer) {9+ describe(`base functionality - ${name}`, () => {10+ let baseState11+ let origBaseState12 12- 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+ })16 17- 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).toMatchObject({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- })21 25- 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+ })29 32- 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, () => "")36 35- it("should return a copy when modifying stuff", () => {36- debugger37- const nextState = immer(baseState, s => {38- s.aProp = "hello world"37+ expect(warning).toHaveBeenCalledTimes(4)38+ warning.mockClear()39 })40- expect(nextState).not.toBe(baseState)41- expect(baseState.aProp).toBe("hi")42- expect(nextState.aProp).toBe("hello world")43- // structural sharing?44- expect(nextState.nested).toBe(baseState.nested)45- })40 47- it("deep change bubbles up", () => {48- debugger49- const nextState = immer(baseState, s => {50- 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 })52- expect(nextState).not.toBe(baseState)53- expect(nextState.anObject).not.toBe(baseState.anObject)54- expect(baseState.anObject.nested.yummie).toBe(true)55- expect(nextState.anObject.nested.yummie).toBe(false)56- expect(nextState.anArray).toBe(baseState.anArray)57- })51 59- it("can add props", () => {60- const nextState = immer(baseState, s => {61- 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 })63- expect(nextState).not.toBe(baseState)64- expect(nextState.anObject).not.toBe(baseState.anObject)65- expect(nextState.anObject.nested).toBe(baseState.anObject.nested)66- expect(nextState.anObject.cookie).toEqual({tasty: true})67- })62 69- it("can delete props", () => {70- const nextState = immer(baseState, s => {71- 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 })73- expect(nextState).not.toBe(baseState)74- expect(nextState.anObject).not.toBe(baseState.anObject)75- expect(nextState.anObject.nested).toBe(undefined)76- })72 78- it("ignores single non-modification", () => {79- const nextState = immer(baseState, s => {80- 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 })82- expect(nextState).toBe(baseState)83- })81 85- it("processes single modification", () => {86- const nextState = immer(baseState, s => {87- s.aProp = "hello"88- 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 })90- expect(nextState).not.toBe(baseState)91- expect(nextState).toEqual(baseState)92- })88 94- it("should support reading arrays", () => {95- const nextState = immer(baseState, s => {96- 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 })98- expect(nextState.anArray).toBe(baseState.anArray)99- expect(nextState).toBe(baseState)100- })97 102- it("should support changing arrays", () => {103- const nextState = immer(baseState, s => {104- 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 })106- expect(nextState).not.toBe(baseState)107- expect(nextState.anArray).not.toBe(baseState.anArray)108- expect(nextState.anArray[3]).toEqual(true)109- })105 111- it("should support changing arrays - 2", () => {112- const nextState = immer(baseState, s => {113- 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 })115- expect(nextState).not.toBe(baseState)116- expect(nextState.anArray).not.toBe(baseState.anArray)114 115+ it("should support changing arrays - 2", () => {116+ const nextState = immer(baseState, s => {118- expect(nextState.anArray).toEqual([3, "a", "b", {c: 3}, 1])119- })117+ s.anArray.splice(1, 1, "a", "b")118+ })119+ expect(nextState).not.toBe(baseState)120+ expect(nextState.anArray).not.toBe(baseState.anArray)121 121- it("should support sorting arrays", () => {122- const nextState = immer(baseState, s => {123- s.anArray[2].c = 4124- s.anArray.sort()125- s.anArray[3].c = 5122+ expect(nextState.anArray).toEqual([3, "a", "b", {c: 3}, 1])123 })127- expect(nextState).not.toBe(baseState)128- expect(nextState.anArray).not.toBe(baseState.anArray)129- expect(nextState.anArray).toEqual([1, 2, 3, {c: 5}])130- })124 132- it("should updating inside arrays", () => {133- const nextState = immer(baseState, s => {134- 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 })136- expect(nextState).not.toBe(baseState)137- expect(nextState.anArray).not.toBe(baseState.anArray)138- expect(nextState.anArray).toEqual([3, 2, {c: 3, test: true}, 1])139- })135 141- it("reusing object should work", () => {142- const nextState = immer(baseState, s => {143- const obj = s.anObject144- delete s.anObject145- 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 })147- expect(nextState).not.toBe(baseState)148- expect(nextState.anArray).toBe(baseState.anArray)149- expect(nextState).toEqual({150- anArray: [3, 2, {c: 3}, 1],151- aProp: "hi",152- messy: {153- nested: {154- yummie: true155- },156- coffee: false157- }158- })159- expect(nextState.messy.nested).toBe(baseState.anObject.nested)160- })144 162- it("refs should be transparent", () => {163- const nextState = immer(baseState, s => {164- const obj = s.anObject165- s.aProp = "hello"166- delete s.anObject167- obj.coffee = true168- 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 })170- expect(nextState).not.toBe(baseState)171- expect(nextState.anArray).toBe(baseState.anArray)172- expect(nextState).toEqual({173- anArray: [3, 2, {c: 3}, 1],174- aProp: "hello",175- messy: {176- nested: {177- yummie: true178- },179- coffee: true180- }181- })182- expect(nextState.messy.nested).toBe(baseState.anObject.nested)183- })165 185- it("should allow setting to undefined a defined draft property", () => {186- const nextState = immer(baseState, s => {187- 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 })189- expect(nextState).not.toBe(baseState)190- expect(baseState.aProp).toBe("hi")191- expect(nextState.aProp).toBe(undefined)192- })188 194- // ES implementation does't protect against all outside modifications, just some..195- it.skip("should revoke the proxy of the baseState after immer function is executed", () => {196- let proxy197- const nextState = immer(baseState, s => {198- proxy = s199- 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 })201- expect(nextState).not.toBe(baseState)202- expect(baseState.aProp).toBe("hi")203- expect(nextState.aProp).toBe("hello")197 205- expect(() => {206- proxy.aProp = "Hallo"207- }).toThrowError(/revoked/)208- expect(() => {209- const aProp = proxy.aProp210- }).toThrowError(/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")209 212- expect(nextState).not.toBe(baseState)213- expect(baseState.aProp).toBe("hi")214- expect(nextState.aProp).toBe("hello")215- })210+ expect(() => {211+ proxy.aProp = "Hallo"212+ }).toThrowError(/revoked/)213+ expect(() => {214+ const aProp = proxy.aProp215+ }).toThrowError(/revoked/)216 217+ expect(nextState).not.toBe(baseState)218+ expect(baseState.aProp).toBe("hi")219+ expect(nextState.aProp).toBe("hello")220+ })221+ }222+217- it("should revoke the proxy of the baseState after immer function is executed - 2", () => {218- let proxy219- const nextState = immer(baseState, s => {220- 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 })222- expect(nextState).toBe(baseState)223- expect(() => {224- // In ES5 implemenation only protects existing props, but alas..225- proxy.coffee = "Hallo"226- }).toThrowError(/revoked/)227- expect(() => {228- const test = proxy.coffee229- }).toThrowError(/revoked/)230- })237 232- afterEach(() => {233- expect(baseState).toBe(origBaseState)234- expect(baseState).toEqual(createBaseState())235- })238+ afterEach(() => {239+ expect(baseState).toBe(origBaseState)240+ expect(baseState).toEqual(createBaseState())241+ })242 237- function createBaseState() {238- return {239- anArray: [3, 2, {c: 3}, 1],240- aProp: "hi",241- anObject: {242- nested: {243- yummie: true244- },245- 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 }248- }249-})255+ })256+}modified:__tests__/performance.js+28 added-8 removed
1223456763 unmodified lines717273747475767576777879808182838384858485868788899090919293949596979899100101102103104105106107108109110111112"use strict"import immer, {setAutoFreeze} from ".."import immerProxy, {setAutoFreeze as setAutoFreezeProxy} from ".."import immerEs5, {setAutoFreeze as setAutoFreezeEs5} from "../es5"import cloneDeep from "lodash.clonedeep"import {List, Record} from "immutable"
describe("performance", () => {63 unmodified lines } }) })
test("immer - with autofreeze", () => { setAutoFreeze(true) immer(frozenBazeState, draft => { test("immer (proxy) - with autofreeze", () => { setAutoFreezeProxy(true) immerProxy(frozenBazeState, draft => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } }) })
test("immer - without autofreeze", () => { setAutoFreeze(false) immer(baseState, draft => { test("immer (proxy) - without autofreeze", () => { setAutoFreezeProxy(false) immerProxy(baseState, draft => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } }) setAutoFreeze(true) setAutoFreezeProxy(true) })
test("immer (es5) - with autofreeze", () => { setAutoFreezeEs5(true) immerEs5(frozenBazeState, draft => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } }) })
test("immer (es5) - without autofreeze", () => { setAutoFreezeEs5(false) immerEs5(baseState, draft => { for (let i = 0; i < MAX * MODIFY_FACTOR; i++) { draft[i].done = true } }) setAutoFreezeEs5(true) })})added:es5.js+259 added
1+"use strict"2+// @ts-check3+4+const PROXY_TARGET = Symbol("immer-proxy")5+const CHANGED_STATE = Symbol("immer-changed-state")6+const PARENT = Symbol("immer-parent")7+8+let autoFreeze = true9+10+/**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+ */20+function immer(baseState, thunk) {21+ let finalizing = false22+ let finished = false23+ const descriptors = {}24+ const proxies = []25+26+ // 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+ }38+39+ 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+ }45+46+ 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+ }61+62+ 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+ }101+102+ function createObjectProxy(base) {103+ const proxy = {}104+ Object.keys(base).forEach(prop =>105+ Object.defineProperty(proxy, prop, createPropertyProxy(prop))106+ )107+ return proxy108+ }109+110+ 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+ }116+117+ // 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+ }135+136+ function hasObjectChanges(proxy) {137+ const baseKeys = Object.keys(proxy[PROXY_TARGET])138+ const keys = Object.keys(proxy)139+ return !shallowEqual(baseKeys, keys)140+ }141+142+ function hasArrayChanges(proxy) {143+ return proxy[PROXY_TARGET].length !== proxy.length144+ }145+146+ 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+ }154+155+ function finalizeObject(proxy) {156+ const res = {}157+ Object.keys(proxy).forEach(prop => {158+ res[prop] = finalize(proxy[prop])159+ })160+ return freeze(res)161+ }162+163+ function finalizeArray(proxy) {164+ return freeze(proxy.map(finalize))165+ }166+167+ // 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+}185+186+function 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+}194+195+function isPlainObject(value) {196+ if (value === null || typeof value !== "object") return false197+ const proto = Object.getPrototypeOf(value)198+ return proto === Object.prototype || proto === null199+}200+201+function isProxy(value) {202+ return !!(value && value[PROXY_TARGET])203+}204+205+function freeze(value) {206+ if (autoFreeze) {207+ Object.freeze(value)208+ }209+ return value210+}211+212+function createHiddenProperty(target, prop, value) {213+ Object.defineProperty(target, prop, {214+ value: value,215+ enumerable: false,216+ writable: true217+ })218+}219+220+function 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+}244+245+/**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+ */253+function setAutoFreeze(enableAutoFreeze) {254+ autoFreeze = enableAutoFreeze255+}256+257+createHiddenProperty(exports, "__esModule", true)258+module.exports.default = immer259+module.exports.setAutoFreeze = setAutoFreezedeleted:immer-es5.js-260 removed
1-import {isObject} from "util"2-;("use strict")3-// @ts-check4-5-const PROXY_TARGET = Symbol("immer-proxy") // TODO: create per closure, to avoid sharing proxies between multiple immer version6-const CHANGED_STATE = Symbol("immer-changed-state")7-const PARENT = Symbol("immer-parent")8-9-let autoFreeze = true10-11-/**12- * Immer takes a state, and runs a function against it.13- * That function can freely mutate the state, as it will create copies-on-write.14- * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned15- *16- * @export17- * @param {any} baseState - the state to start with18- * @param {Function} thunk - function that receives a proxy of the base state as first argument and which can be freely modified19- * @returns {any} a new state, or the base state if nothing was modified20- */21-function immer(baseState, thunk) {22- let finalizing = false23- let finished = false24- const descriptors = {}25- const proxies = []26-27- // creates a proxy for plain objects / arrays28- function createProxy(base, parent) {29- let proxy30- if (isPlainObject(base)) proxy = createObjectProxy(base)31- else if (Array.isArray(base)) proxy = createArrayProxy(base)32- else throw new Error("Expected a plain object or array")33- createHiddenProperty(proxy, PROXY_TARGET, base)34- createHiddenProperty(proxy, CHANGED_STATE, false)35- createHiddenProperty(proxy, PARENT, parent)36- proxies.push(proxy)37- return proxy38- }39-40- function assertUnfinished() {41- if (finished)42- throw new Error(43- "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process?"44- )45- }46-47- function proxySet(proxy, prop, value) {48- // immer func not ended?49- assertUnfinished()50- // actually a change?51- if (Object.is(proxy[prop], value)) return52- // mark changed53- markDirty(proxy)54- // and stop proxying, we know this object has changed55- Object.defineProperty(proxy, prop, {56- enumerable: true,57- writable: true,58- configurable: true,59- value: value60- })61- }62-63- function createPropertyProxy(prop) {64- return (65- descriptors[prop] ||66- (descriptors[prop] = {67- configurable: true,68- enumerable: true,69- get() {70- assertUnfinished()71- // find the target object72- const target = this[PROXY_TARGET]73- // find the original value74- const value = target[prop]75- // if we are finalizing, don't bother creating proxies, just return base value76- if (finalizing) return value77- // if not proxy-able, return value78- if (!isPlainObject(value) && !Array.isArray(value))79- return value80- // otherwise, create proxy81- const proxy = createProxy(value, this)82- // and make sure this proxy is returned from this prop in the future if read83- // (write behavior as is)84- Object.defineProperty(this, prop, {85- configurable: true,86- enumerable: true,87- get() {88- return proxy89- },90- set(value) {91- proxySet(this, prop, value)92- }93- })94- return proxy95- },96- set(value) {97- proxySet(this, prop, value)98- }99- })100- )101- }102-103- function createObjectProxy(base) {104- const proxy = {}105- Object.keys(base).forEach(prop =>106- Object.defineProperty(proxy, prop, createPropertyProxy(prop))107- )108- return proxy109- }110-111- function createArrayProxy(base) {112- const proxy = []113- for (let i = 0; i < base.length; i++)114- Object.defineProperty(proxy, "" + i, createPropertyProxy("" + i))115- return proxy116- }117-118- // this sounds very expensive, but actually it is not that extensive in practice119- // as it will only visit proxies, and only do key-based change detection for objects for120- // which it is not already know that they are changed (that is, only object for which no known key was changed)121- function markChanges() {122- // intentionally we process the proxies in reverse order;123- // ideally we start by processing leafs in the tree, because if a child has changed, we don't have to check the parent anymore124- // reverse order of proxy creation approximates this125- for (let i = proxies.length - 1; i >= 0; i--) {126- const proxy = proxies[i]127- if (128- proxy[CHANGED_STATE] === false &&129- ((isPlainObject(proxy) && hasObjectChanges(proxy)) ||130- (Array.isArray(proxy) && hasArrayChanges(proxy)))131- ) {132- markDirty(proxy)133- }134- }135- }136-137- function hasObjectChanges(proxy) {138- const baseKeys = Object.keys(proxy[PROXY_TARGET])139- const keys = Object.keys(proxy)140- return !shallowEqual(baseKeys, keys)141- }142-143- function hasArrayChanges(proxy) {144- return proxy[PROXY_TARGET].length !== proxy.length145- }146-147- function finalize(proxy) {148- // given a base object, returns it if unmodified, or return the changed cloned if modified149- if (!isProxy(proxy)) return proxy150- if (!proxy[CHANGED_STATE]) return proxy[PROXY_TARGET] // return the original target151- if (isPlainObject(proxy)) return finalizeObject(proxy)152- if (Array.isArray(proxy)) return finalizeArray(proxy)153- throw new Error("Illegal state")154- }155-156- function finalizeObject(proxy) {157- const res = {}158- Object.keys(proxy).forEach(prop => {159- res[prop] = finalize(proxy[prop])160- })161- return freeze(res)162- }163-164- function finalizeArray(proxy) {165- return freeze(proxy.map(finalize))166- }167-168- // create proxy for root169- const rootClone = createProxy(baseState, undefined)170- // execute the thunk171- const maybeVoidReturn = thunk(rootClone)172- //values either than undefined will trigger warning;173- !Object.is(maybeVoidReturn, undefined) &&174- console.warn(175- `Immer callback expects no return value. However ${typeof maybeVoidReturn} was returned`176- )177- // and finalize the modified proxy178- finalizing = true179- // find and mark all changes (for parts not done yet)180- markChanges()181- const res = finalize(rootClone)182- // make sure all proxies become unusable183- finished = true184- return res185-}186-187-function markDirty(proxy) {188- proxy[CHANGED_STATE] = true189- let parent = proxy190- while ((parent = parent[PARENT])) {191- if (parent[CHANGED_STATE] === true) return192- parent[CHANGED_STATE] = true193- }194-}195-196-function isPlainObject(value) {197- if (value === null || typeof value !== "object") return false198- const proto = Object.getPrototypeOf(value)199- return proto === Object.prototype || proto === null200-}201-202-function isProxy(value) {203- return !!(value && value[PROXY_TARGET])204-}205-206-function freeze(value) {207- if (autoFreeze) {208- Object.freeze(value)209- }210- return value211-}212-213-function createHiddenProperty(target, prop, value) {214- Object.defineProperty(target, prop, {215- value: value,216- enumerable: false,217- writable: true218- })219-}220-221-function shallowEqual(objA, objB) {222- //From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js223- if (Object.is(objA, objB)) return true224- if (225- typeof objA !== "object" ||226- objA === null ||227- typeof objB !== "object" ||228- objB === null229- ) {230- return false231- }232- const keysA = Object.keys(objA)233- const keysB = Object.keys(objB)234- if (keysA.length !== keysB.length) return false235- for (let i = 0; i < keysA.length; i++) {236- if (237- !hasOwnProperty.call(objB, keysA[i]) ||238- !Object.is(objA[keysA[i]], objB[keysA[i]])239- ) {240- return false241- }242- }243- return true244-}245-246-/**247- * Automatically freezes any state trees generated by immer.248- * This protects against accidental modifications of the state tree outside of an immer function.249- * This comes with a performance impact, so it is recommended to disable this option in production.250- * It is by default enabled.251- *252- * @returns {void}253- */254-function setAutoFreeze(enableAutoFreeze) {255- autoFreeze = enableAutoFreeze256-}257-258-createHiddenProperty(exports, "__esModule", true)259-module.exports.default = immer260-module.exports.setAutoFreeze = setAutoFreezemodified:immer.js+5 added
1 "use strict"2 // @ts-check3 4+if (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+ )8+9 /**10 * @typedef {Object} RevocableProxy11 * @property {any} proxy12 * @property {Function} revoke216 unmodified linesmodified:package.json+2 added-1 removed
12345567891011121339 unmodified lines{ "name": "immer", "version": "0.1.2", "description": "Create your next immutable state by mutating the current one", "main": "immer-es5.js", "main": "immer.js", "types": "./index.d.ts", "scripts": { "test": "jest", "test:perf": "jest --verbose __tests__/performance.js", "prettier": "prettier \"*/**/*.js\" --ignore-path ./.prettierignore --write && git add . && git status" }, "pre-commit": [ "prettier"39 unmodified linesmodified:readme.md+36 added-8 removed
15 unmodified lines16 Using immer is like having a personal assistant; he takes a letter (the current state), and gives you a copy (draft) to jot changes onto. Once you are done, the assistant will take your draft and produce the real immutable, final letter for you (the next state).17 18 A 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.19 20+## Installation21+22+`npm install immer`23+24 ## API25 26 The immer package exposes a single function:27 1 unmodified line29 30 ## Example31 32 ```javascript33+import immer from "immer"34+35 const baseState = [36 {37 todo: "Learn typescript",38 done: true27 unmodified lines66 // changed data not (dûh)67 expect(nextState[1]).not.toBe(baseState[1])68 ```69 70+## Using immer on older JavaScript environments71+72+By default `immer` tries to use proxies for optimal performance.73+However, on older JavaScript engines `Proxy` is not available.74+For example, Microsoft Internet Explorer or React Native on Android.75+In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:76+77+```javascript78+import immer from "immer/es5"79+```80+81 ## Benefits82 83 * Use the language© to construct create your next state84+* Use JavaScript native arrays and object85+* Automatic immutability; any state tree produced by `immer` will by defualt be deeply frozen86 * Strongly typed, no string based paths etc87 * Deep updates are trivial88 * Small, dependency free library with minimal api surface89 * No accidental mutations of current state, but intentional mutations of a draft state8 unmodified lines98 Use `setAutoFreeze(true / false)` to turn this feature on or off.99 100 ## Reducer Example101 83-A lot of words; here is a simple example of the difference that this approach could make in practice.102+Here is a simple example of the difference that this approach could make in practice.103 The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)104 105 _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)_106 69 unmodified lines176 This test takes 100.000 todo items, and updates 10.000 of them.177 These tests were executed on Node 8.4.0178 179 ```161- performance162- ✓ just mutate (1ms) // No immutability at all163- ✓ deepclone, then mutate (647ms) // Clone entire tree, then mutate (no structural sharing!)164- ✓ handcrafted reducer (17ms) // Implement it as typical Redux reducer, with slices and spread operator165- ✓ immutableJS (81ms) // Use immutableJS and leverage `withMutations` for best performance166- ✓ immer - with autofreeze (309ms) // Immer, with auto freeze enabled167- ✓ immer - without autofreeze (148ms) // Immer, but without auto freeze enabled180+ ✓ just mutate (2ms)181+ (No immutability at all)182+ ✓ deepclone, then mutate (390ms)183+ (Clone entire tree, then mutate (no structural sharing!))184+ ✓ handcrafted reducer (27ms)185+ (Implement it as typical Redux reducer, with slices and spread operator)186+ ✓ immutableJS (68ms)187+ (Use immutableJS and leverage `withMutations` for best performance)188+ ✓ immer (proxy) - with autofreeze (303ms)189+ (Immer, with auto freeze enabled, default implementation)190+ ✓ immer (proxy) - without autofreeze (142ms)191+ (Immer, with auto freeze disabled, default implementation)192+ ✓ immer (es5) - with autofreeze (414ms)193+ (Immer, with auto freeze enabled, compatibility implementation)194+ ✓ immer (es5) - without autofreeze (341ms)195+ (Immer, with auto freeze disabled, default implementation)196 ```197 198 ## Limitations199 11 unmodified lines