Merge branch 'master' into patches
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parents 9ccefad, d0fd57f · Browse files · 13 files·+590 added−307 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
13 files+590 added−307 removed
- tests:+31 added−2 removed
- other:+559 added−305 removed
Provenance
- Commit
2ddcda2- Tree
6299f79- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent 1
9ccefad- Parent 2
d0fd57f
13 files changed+590 added−307 removed
modified:__performance_tests__/add-data.js+73 added-65 removed
12345678989101112131410111617181213141516171819202122232425262721222324252829303132333435362829303132333738394041424336373839404445464748495043444546475152535455565051575859606162546364565758596061626566676864656667686969707172737475767778798072737475767781828384858687888081828384858990919293949596888990919293979899100101102103"use strict"
import {measure} from "./measure"import produce, {setAutoFreeze, setUseProxies} from "../dist/immer.umd.js"import cloneDeep from "lodash.clonedeep"import {fromJS} from "immutable"import Seamless from "seamless-immutable"import deepFreeze from "deep-freeze"
describe("loading large set of data", () => { const dataSet = require("./data.json") const baseState = { data: null } const frozenBazeState = deepFreeze(cloneDeep(baseState)) const immutableJsBaseState = fromJS(baseState)console.log("# add-data - loading large set of data")
function measure(name, fn) { global.gc && global.gc() test(name, fn)const dataSet = require("./data.json")const baseState = { data: null}const frozenBazeState = deepFreeze(cloneDeep(baseState))const immutableJsBaseState = fromJS(baseState)const seamlessBaseState = Seamless.from(baseState)
measure( "just mutate", () => ({draft: cloneDeep(baseState)}), ({draft}) => { draft.data = dataSet })
{ const draft = cloneDeep(baseState) measure("just mutate", () => { draft.data = dataSet })measure( "just mutate, freeze", () => ({draft: cloneDeep(baseState)}), ({draft}) => { draft.data = dataSet deepFreeze(draft) })
{ const draft = cloneDeep(baseState) measure("just mutate, freeze", () => { draft.data = dataSet deepFreeze(draft) })measure("handcrafted reducer (no freeze)", () => { const nextState = { ...baseState, data: dataSet }})
measure("handcrafted reducer (no freeze)", () => { const nextState = { ...baseState, data: dataSet }measure("handcrafted reducer (with freeze)", () => { const nextState = deepFreeze({ ...baseState, data: dataSet })})
measure("handcrafted reducer (with freeze)", () => { const nextState = deepFreeze({ ...baseState, data: dataSet })measure("immutableJS", () => { let state = immutableJsBaseState.withMutations(state => { state.setIn(["data"], fromJS(dataSet)) })})
measure("immutableJS", () => { let state = immutableJsBaseState.withMutations(state => {measure("immutableJS + toJS", () => { let state = immutableJsBaseState .withMutations(state => { state.setIn(["data"], fromJS(dataSet)) }) .toJS() })})
measure("immutableJS + toJS", () => { let state = immutableJsBaseState .withMutations(state => { state.setIn(["data"], fromJS(dataSet)) }) .toJS() })measure("seamless-immutable", () => { seamlessBaseState.set("data", dataSet)})
measure("immer (proxy) - without autofreeze", () => { setUseProxies(true) setAutoFreeze(false) produce(baseState, draft => { draft.data = dataSet })measure("seamless-immutable + asMutable", () => { seamlessBaseState.set("data", dataSet).asMutable({deep: true})})
measure("immer (proxy) - without autofreeze", () => { setUseProxies(true) setAutoFreeze(false) produce(baseState, draft => { draft.data = dataSet })})
measure("immer (proxy) - with autofreeze", () => { setUseProxies(true) setAutoFreeze(true) produce(frozenBazeState, draft => { draft.data = dataSet })measure("immer (proxy) - with autofreeze", () => { setUseProxies(true) setAutoFreeze(true) produce(frozenBazeState, draft => { draft.data = dataSet })})
measure("immer (es5) - without autofreeze", () => { setUseProxies(false) setAutoFreeze(false) produce(baseState, draft => { draft.data = dataSet })measure("immer (es5) - without autofreeze", () => { setUseProxies(false) setAutoFreeze(false) produce(baseState, draft => { draft.data = dataSet })})
measure("immer (es5) - with autofreeze", () => { setUseProxies(false) setAutoFreeze(true) produce(frozenBazeState, draft => { draft.data = dataSet })measure("immer (es5) - with autofreeze", () => { setUseProxies(false) setAutoFreeze(true) produce(frozenBazeState, draft => { draft.data = dataSet })})added:__performance_tests__/incremental.js+133 added
1+"use strict"2+import {measure} from "./measure"3+import produce, {setAutoFreeze, setUseProxies} from "../dist/immer.umd.js"4+import cloneDeep from "lodash.clonedeep"5+import * as Immutable from "immutable"6+7+function createTestObject() {8+ return {9+ a: 1,10+ b: "Some data here"11+ }12+}13+14+const MAX = 100015+const baseState = {16+ ids: [],17+ map: Object.create(null)18+}19+20+let immutableJsBaseState21+22+immutableJsBaseState = {23+ ids: Immutable.List(),24+ map: Immutable.Map()25+}26+27+measure(28+ "just mutate",29+ () => cloneDeep(baseState),30+ draft => {31+ for (let i = 0; i < MAX; i++) {32+ draft.ids.push(i)33+ draft.map[i] = createTestObject()34+ }35+ }36+)37+38+measure(39+ "handcrafted reducer",40+ () => cloneDeep(baseState),41+ state => {42+ for (let i = 0; i < MAX; i++) {43+ state = {44+ ids: [...state.ids, i],45+ map: {46+ ...state.map,47+ [i]: createTestObject()48+ }49+ }50+ }51+ }52+)53+54+measure(55+ "immutableJS",56+ () => immutableJsBaseState,57+ state => {58+ for (let i = 0; i < MAX; i++) {59+ state = {60+ ids: state.ids.push(i),61+ map: state.map.set(i, createTestObject())62+ }63+ }64+ }65+)66+67+measure(68+ "immer (proxy)",69+ () => {70+ setUseProxies(true)71+ setAutoFreeze(false)72+ return baseState73+ },74+ state => {75+ for (let i = 0; i < MAX; i++) {76+ state = produce(state, draft => {77+ draft.ids.push(i)78+ draft.map[i] = createTestObject()79+ })80+ }81+ }82+)83+84+measure(85+ "immer (es5)",86+ () => {87+ setUseProxies(false)88+ setAutoFreeze(false)89+ return baseState90+ },91+ state => {92+ for (let i = 0; i < MAX; i++) {93+ state = produce(state, draft => {94+ draft.ids.push(i)95+ draft.map[i] = createTestObject()96+ })97+ }98+ }99+)100+101+measure(102+ "immer (proxy) - single produce",103+ () => {104+ setUseProxies(true)105+ setAutoFreeze(false)106+ return baseState107+ },108+ state => {109+ produce(state, draft => {110+ for (let i = 0; i < MAX; i++) {111+ draft.ids.push(i)112+ draft.map[i] = createTestObject()113+ }114+ })115+ }116+)117+118+measure(119+ "immer (es5) - single produce",120+ () => {121+ setUseProxies(false)122+ setAutoFreeze(false)123+ return baseState124+ },125+ state => {126+ produce(state, draft => {127+ for (let i = 0; i < MAX; i++) {128+ draft.ids.push(i)129+ draft.map[i] = createTestObject()130+ }131+ })132+ }133+)added:__performance_tests__/measure.js+20 added
1234567891011121314151617181920"use strict"
function measureTime(setup, fn) { if (!fn) { fn = setup setup = () => {} } const args = setup() global.gc && global.gc() const startTime = Date.now() fn(args) const endTime = Date.now() return endTime - startTime}
export function measure(name, setup, fn) { const times = [...Array(5)].map(() => measureTime(setup, fn)) const medianTime = times.sort()[Math.round(times.length / 2)] console.log(`${name}: ${medianTime}ms`)}modified:__performance_tests__/todo.js+162 added-110 removed
1 "use strict"2+3+import {measure} from "./measure"4 import produce, {setAutoFreeze, setUseProxies} from "../dist/immer.umd.js"5 import cloneDeep from "lodash.clonedeep"6 import {List, Record} from "immutable"7+import Seamless from "seamless-immutable"8 import deepFreeze from "deep-freeze"9 10 function freeze(x) {11 Object.freeze(x)12 return x13 }14 12-describe("performance", () => {13- const MAX = 10000014- const MODIFY_FACTOR = 0.115- const baseState = []16- let frozenBazeState17- let immutableJsBaseState15+const MAX = 5000016+const MODIFY_FACTOR = 0.117+const baseState = []18+let frozenBazeState19+let immutableJsBaseState20+let seamlessBaseState21 19- // produce the base state20- for (let i = 0; i < MAX; i++) {21- baseState.push({22- todo: "todo_" + i,23- done: false,24- someThingCompletelyIrrelevant: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]25- })26- }27-28- // Produce the frozen bazeState29- frozenBazeState = deepFreeze(cloneDeep(baseState))30-31- // generate immutalbeJS base state32- const todoRecord = Record({33- todo: "",22+// produce the base state23+for (let i = 0; i < MAX; i++) {24+ baseState.push({25+ todo: "todo_" + i,26 done: false,35- someThingCompletelyIrrelevant: []27+ someThingCompletelyIrrelevant: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]28 })37- immutableJsBaseState = List(baseState.map(todo => todoRecord(todo)))29+}30 39- function measure(name, fn) {40- global.gc && global.gc()41- test(name, fn)42- }31+// Produce the frozen bazeState32+frozenBazeState = deepFreeze(cloneDeep(baseState))33 44- {45- const draft = cloneDeep(baseState)46- measure("just mutate", () => {47- for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {48- draft[i].done = true49- }50- })51- }34+// generate immutalbeJS base state35+const todoRecord = Record({36+ todo: "",37+ done: false,38+ someThingCompletelyIrrelevant: []39+})40+immutableJsBaseState = List(baseState.map(todo => todoRecord(todo)))41 53- {54- const draft = cloneDeep(baseState)55- measure("just mutate, freeze", () => {56- for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {57- draft[i].done = true58- }59- deepFreeze(draft)60- })61- }42+// generate seamless-immutable base state43+seamlessBaseState = Seamless.from(baseState)44 63- measure("deepclone, then mutate", () => {64- const draft = cloneDeep(baseState)45+console.log("# todo - performance")46+47+measure(48+ "just mutate",49+ () => ({draft: cloneDeep(baseState)}),50+ ({draft}) => {51 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {52 draft[i].done = true53 }68- })54+ }55+)56 70- measure("deepclone, then mutate, then freeze", () => {71- const draft = cloneDeep(baseState)57+measure(58+ "just mutate, freeze",59+ () => ({draft: cloneDeep(baseState)}),60+ ({draft}) => {61 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {62 draft[i].done = true63 }64 deepFreeze(draft)76- })65+ }66+)67 68+measure("deepclone, then mutate", () => {69+ const draft = cloneDeep(baseState)70+ for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {71+ draft[i].done = true72+ }73+})74+75+measure("deepclone, then mutate, then freeze", () => {76+ const draft = cloneDeep(baseState)77+ for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {78+ draft[i].done = true79+ }80+ deepFreeze(draft)81+})82+78- measure("handcrafted reducer (no freeze)", () => {79- const nextState = [80- ...baseState.slice(0, MAX * MODIFY_FACTOR).map(todo => ({83+measure("handcrafted reducer (no freeze)", () => {84+ const nextState = [85+ ...baseState.slice(0, MAX * MODIFY_FACTOR).map(todo => ({86+ ...todo,87+ done: true88+ })),89+ ...baseState.slice(MAX * MODIFY_FACTOR)90+ ]91+})92+93+measure("handcrafted reducer (with freeze)", () => {94+ const nextState = freeze([95+ ...baseState.slice(0, MAX * MODIFY_FACTOR).map(todo =>96+ freeze({97 ...todo,98 done: true83- })),84- ...baseState.slice(MAX * MODIFY_FACTOR)85- ]86- })99+ })100+ ),101+ ...baseState.slice(MAX * MODIFY_FACTOR)102+ ])103+})104 88- measure("handcrafted reducer (with freeze)", () => {89- const nextState = freeze([90- ...baseState.slice(0, MAX * MODIFY_FACTOR).map(todo =>91- freeze({92- ...todo,93- done: true94- })95- ),96- ...baseState.slice(MAX * MODIFY_FACTOR)97- ])105+measure("naive handcrafted reducer (without freeze)", () => {106+ const nextState = baseState.map((todo, index) => {107+ if (index < MAX * MODIFY_FACTOR)108+ return {109+ ...todo,110+ done: true111+ }112+ else return todo113 })114+})115 100- measure("naive handcrafted reducer (without freeze)", () => {101- const nextState = baseState.map((todo, index) => {116+measure("naive handcrafted reducer (with freeze)", () => {117+ const nextState = deepFreeze(118+ baseState.map((todo, index) => {119 if (index < MAX * MODIFY_FACTOR)120 return {121 ...todo,122 done: true123 }124 else return todo125 })109- })126+ )127+})128 111- measure("naive handcrafted reducer (with freeze)", () => {112- const nextState = deepFreeze(113- baseState.map((todo, index) => {114- if (index < MAX * MODIFY_FACTOR)115- return {116- ...todo,117- done: true118- }119- else return todo120- })121- )129+measure("immutableJS", () => {130+ let state = immutableJsBaseState131+ state.withMutations(state => {132+ for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {133+ state.setIn([i, "done"], true)134+ }135 })136+})137 124- measure("immutableJS", () => {125- let state = immutableJsBaseState126- state.withMutations(state => {138+measure("immutableJS + toJS", () => {139+ let state = immutableJsBaseState140+ .withMutations(state => {141 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {142 state.setIn([i, "done"], true)143 }144 })145+ .toJS()131- })146+})147 133- measure("immutableJS + toJS", () => {134- let state = immutableJsBaseState135- .withMutations(state => {136- for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {137- state.setIn([i, "done"], true)138- }139- })140- .toJS()148+measure("seamless-immutable", () => {149+ const state = seamlessBaseState150+ state.map((todo, index) => {151+ if (index < MAX * MODIFY_FACTOR) return todo.set("done", true)152+ else return todo153 })154+})155 143- measure("immer (proxy) - without autofreeze", () => {156+measure("seamless-immutable + asMutable", () => {157+ const state = seamlessBaseState158+ state159+ .map((todo, index) => {160+ if (index < MAX * MODIFY_FACTOR) return todo.set("done", true)161+ else return todo162+ })163+ .asMutable({deep: true})164+})165+166+measure(167+ "immer (proxy) - without autofreeze",168+ () => {169 setUseProxies(true)170 setAutoFreeze(false)171+ },172+ () => {173 produce(baseState, draft => {174 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {175 draft[i].done = true176 }177 })151- })178+ }179+)180 153- measure("immer (proxy) - with autofreeze", () => {181+measure(182+ "immer (proxy) - with autofreeze",183+ () => {184 setUseProxies(true)185 setAutoFreeze(true)186+ },187+ () => {188 produce(frozenBazeState, draft => {189 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {190 draft[i].done = true191 }192 })161- })193+ }194+)195 163- measure("immer (proxy) - w/o autofreeze - with patch listener", () => {196+measure(197+ "immer (proxy) - without autofreeze - with patch listener",198+ () => {199 setUseProxies(true)200 setAutoFreeze(false)201+ },202+ () => {203 produce(167- frozenBazeState,204+ baseState,205 draft => {206 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {207 draft[i].done = true208 }209 },173- () => {}210+ function() {}211 )175- })212+ }213+)214 177- measure("immer (es5) - without autofreeze", () => {215+measure(216+ "immer (es5) - without autofreeze",217+ () => {218 setUseProxies(false)219 setAutoFreeze(false)220+ },221+ () => {222 produce(baseState, draft => {223 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {224 draft[i].done = true225 }226 })185- })227+ }228+)229 187- measure("immer (es5) - with autofreeze", () => {230+measure(231+ "immer (es5) - with autofreeze",232+ () => {233 setUseProxies(false)234 setAutoFreeze(true)235+ },236+ () => {237 produce(frozenBazeState, draft => {238 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {239 draft[i].done = true240 }241 })195- })242+ }243+)244 197- measure("immer (es5) - w/o autofreeze - with patch listener", () => {245+measure(246+ "immer (es5) - without autofreeze - with patch listener",247+ () => {248 setUseProxies(false)249 setAutoFreeze(false)250+ },251+ () => {252 produce(201- frozenBazeState,253+ baseState,254 draft => {255 for (let i = 0; i < MAX * MODIFY_FACTOR; i++) {256 draft[i].done = true257 }258 },207- () => {}259+ function() {}260 )209- })210-})261+ }262+)modified:__tests__/flow/flow.js.flow+13 added-1 removed
1 // @flow2-import produce, {setAutoFreeze, setUseProxies} from "../../src/immer"2+import produce, {setAutoFreeze, setUseProxies, produce as produce2} from "../../src/immer"3 4 setAutoFreeze(true)5 setUseProxies(true)6 66 unmodified lines73 74 // $ExpectError75 f2(undefined, 3)76 }77+78+{79+ // $ExpectError80+ produce2({x: 3})81+82+ const result = produce2({x: 3}, draft => {83+ draft.x = 484+85+ // $ExpectError86+ console.log(draft.y)87+ })88+}modified:__tests__/types.ts+18 added-1 removed
11234559 unmodified lines656667686970717273747576777879808182838485import produce from '../src/immer';import produce, { produce as produce2} from '../src/immer';
interface State { readonly num: number; readonly foo?: string;59 unmodified lines })(state); expect(newState).not.toBe(state); expect(newState).toEqual(expectedState);});
it('can update use the non-default export', () => { const newState = produce2<State>(draft => { draft.num++; draft.foo = 'bar'; draft.bar = 'foo'; draft.baz.x++; draft.baz.y++; draft.arr[0].value = 'foo'; draft.arr.push({ value: 'asf' }); draft.arr2[0].value = 'foo'; draft.arr2.push({ value: 'asf' }); })(state); expect(newState).not.toBe(state); expect(newState).toEqual(expectedState);});modified:src/immer.d.ts+76 added-72 removed
9 unmodified lines10 T extends object ? DraftObject<T> :11 T;12 13 export interface Patch {14- op: "replace" | "remove",14+ op: "replace" | "remove" | "add",15 path: (string|number)[]16 value?: any17 }18 19 export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void20 21-/**22- * Immer takes a state, and runs a function against it.23- * That function can freely mutate the state, as it will create copies-on-write.24- * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.25- *26- * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe27- * any time it is called with the current state.28- *29- * In it's base form immer can receive a patch handler30- *31- * @param currentState - the state to start with32- * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified33- * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined34- * @returns The next state: a new state, or the current state if nothing was modified35- */36-export default function<S = any>(37- currentState: S,38- recipe: (this: Draft<S>, draftState: Draft<S>) => void | S,39- patchListener?: PatchListener40-): S21+export interface IProduce {22+ /**23+ * Immer takes a state, and runs a function against it.24+ * That function can freely mutate the state, as it will create copies-on-write.25+ * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.26+ *27+ * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe28+ * any time it is called with the current state.29+ *30+ * @param currentState - the state to start with31+ * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified32+ * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined33+ * @returns The next state: a new state, or the current state if nothing was modified34+ */35+ <S = any>(36+ currentState: S,37+ recipe: (this: Draft<S>, draftState: Draft<S>) => void | S,38+ listener?: PatchListener39+ ): S40 42-// curried invocations with default initial state43-// 0 additional arguments44-export default function<S = any>(45- recipe: (this: Draft<S>, draftState: Draft<S>) => void | S,46- initialState: S47-): (currentState: S | undefined) => S48-// 1 additional argument of type A49-export default function<S = any, A = any>(50- recipe: (this: Draft<S>, draftState: Draft<S>, a: A) => void | S,51- initialState: S52-): (currentState: S | undefined, a: A) => S53-// 2 additional arguments of types A and B54-export default function<S = any, A = any, B = any>(55- recipe: (this: Draft<S>, draftState: Draft<S>, a: A, b: B) => void | S,56- initialState: S57-): (currentState: S | undefined, a: A, b: B) => S58-// 3 additional arguments of types A, B and C59-export default function<S = any, A = any, B = any, C = any>(60- recipe: (this: Draft<S>, draftState: Draft<S>, a: A, b: B, c: C) => void | S,61- initialState: S62-): (currentState: S | undefined, a: A, b: B, c: C) => S63-// any number of additional arguments, but with loss of type safety64-// this may be alleviated if "variadic kinds" makes it into Typescript:65-// https://github.com/Microsoft/TypeScript/issues/545366-export default function<S = any>(67- recipe: (this: Draft<S>, draftState: Draft<S>, ...extraArgs: any[]) => void | S,68- initialState: S69-): (currentState: S | undefined, ...extraArgs: any[]) => S41+ // curried invocations with default initial state42+ // 0 additional arguments43+ <S = any>(44+ recipe: (this: Draft<S>, draftState: Draft<S>) => void | S,45+ initialState: S46+ ): (currentState: S | undefined) => S47+ // 1 additional argument of type A48+ <S = any, A = any>(49+ recipe: (this: Draft<S>, draftState: Draft<S>, a: A) => void | S,50+ initialState: S51+ ): (currentState: S | undefined, a: A) => S52+ // 2 additional arguments of types A and B53+ <S = any, A = any, B = any>(54+ recipe: (this: Draft<S>, draftState: Draft<S>, a: A, b: B) => void | S,55+ initialState: S56+ ): (currentState: S | undefined, a: A, b: B) => S57+ // 3 additional arguments of types A, B and C58+ <S = any, A = any, B = any, C = any>(59+ recipe: (this: Draft<S>, draftState: Draft<S>, a: A, b: B, c: C) => void | S,60+ initialState: S61+ ): (currentState: S | undefined, a: A, b: B, c: C) => S62+ // any number of additional arguments, but with loss of type safety63+ // this may be alleviated if "variadic kinds" makes it into Typescript:64+ // https://github.com/Microsoft/TypeScript/issues/545365+ <S = any>(66+ recipe: (this: Draft<S>, draftState: Draft<S>, ...extraArgs: any[]) => void | S,67+ initialState: S68+ ): (currentState: S | undefined, ...extraArgs: any[]) => S69 71-// curried invocations without default initial state72-// 0 additional arguments73-export default function<S = any>(74- recipe: (this: Draft<S>, draftState: Draft<S>) => void | S75-): (currentState: S) => S76-// 1 additional argument of type A77-export default function<S = any, A = any>(78- recipe: (this: Draft<S>, draftState: Draft<S>, a: A) => void | S79-): (currentState: S, a: A) => S80-// 2 additional arguments of types A and B81-export default function<S = any, A = any, B = any>(82- recipe: (this: Draft<S>, draftState: Draft<S>, a: A, b: B) => void | S83-): (currentState: S, a: A, b: B) => S84-// 3 additional arguments of types A, B and C85-export default function<S = any, A = any, B = any, C = any>(86- recipe: (this: Draft<S>, draftState: Draft<S>, a: A, b: B, c: C) => void | S87-): (currentState: S, a: A, b: B, c: C) => S88-// any number of additional arguments, but with loss of type safety89-// this may be alleviated if "variadic kinds" makes it into Typescript:90-// https://github.com/Microsoft/TypeScript/issues/545391-export default function<S = any>(92- recipe: (this: Draft<S>, draftState: Draft<S>, ...extraArgs: any[]) => void | S93-): (currentState: S, ...extraArgs: any[]) => S70+ // curried invocations without default initial state71+ // 0 additional arguments72+ <S = any>(73+ recipe: (this: Draft<S>, draftState: Draft<S>) => void | S74+ ): (currentState: S) => S75+ // 1 additional argument of type A76+ <S = any, A = any>(77+ recipe: (this: Draft<S>, draftState: Draft<S>, a: A) => void | S78+ ): (currentState: S, a: A) => S79+ // 2 additional arguments of types A and B80+ <S = any, A = any, B = any>(81+ recipe: (this: Draft<S>, draftState: Draft<S>, a: A, b: B) => void | S82+ ): (currentState: S, a: A, b: B) => S83+ // 3 additional arguments of types A, B and C84+ <S = any, A = any, B = any, C = any>(85+ recipe: (this: Draft<S>, draftState: Draft<S>, a: A, b: B, c: C) => void | S86+ ): (currentState: S, a: A, b: B, c: C) => S87+ // any number of additional arguments, but with loss of type safety88+ // this may be alleviated if "variadic kinds" makes it into Typescript:89+ // https://github.com/Microsoft/TypeScript/issues/545390+ <S = any>(91+ recipe: (this: Draft<S>, draftState: Draft<S>, ...extraArgs: any[]) => void | S92+ ): (currentState: S, ...extraArgs: any[]) => S93+}94+95+export const produce: IProduce96+export default produce97+98 /**99 * Automatically freezes any state trees generated by immer.100 * This protects against accidental modifications of the state tree outside of an immer function.101 * This comes with a performance impact, so it is recommended to disable this option in production.9 unmodified linesmodified:src/immer.js+4 added-1 removed
11 unmodified lines12 *13 * @export14 * @param {any} baseState - the state to start with15 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified16+ * @param {Function} patchListener - optional function that will be called with all the patches produces here17 * @returns {any} a new state, or the base state if nothing was modified18 */18-export default function produce(baseState, producer, patchListener) {19+export function produce(baseState, producer, patchListener) {20 // prettier-ignore21 if (arguments.length < 1 || arguments.length > 3) throw new Error("produce expects 1 to 3 arguments, got " + arguments.length)22 23 // curried invocation39 unmodified lines63 ? produceProxy(baseState, producer, patchListener)64 : produceEs5(baseState, producer, patchListener)65 }66 67+export default produce68+69 export const applyPatches = produce(applyPatchesImpl)modified:src/immer.js.flow+60 added-54 removed
1 // @flow2 3+interface IProduce {4+ /**5+ * Immer takes a state, and runs a function against it.6+ * That function can freely mutate the state, as it will create copies-on-write.7+ * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.8+ *9+ * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe10+ * any time it is called with the current state.11+ *12+ * @param currentState - the state to start with13+ * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified14+ * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined15+ * @returns The next state: a new state, or the current state if nothing was modified16+ */17+ <S>(18+ currentState: S,19+ recipe: (draftState: S) => S | void20+ ): S;21+ // curried invocations with inital state22+ <S, A, B, C>(23+ recipe: (draftState: S, a: A, b: B, c: C) => S | void,24+ initialState: S25+ ): (currentState: S | void, a: A, b: B, c: C) => S;26+ <S, A, B>(27+ recipe: (draftState: S, a: A, b: B) => S | void,28+ initialState: S29+ ): (currentState: S | void, a: A, b: B) => S;30+ <S, A>(31+ recipe: (draftState: S, a: A) => S | void,32+ initialState: S33+ ): (currentState: S | void, a: A) => S;34+ <S>(35+ recipe: (draftState: S) => S | void,36+ initialState: S37+ ): (currentState: S | void) => S;38+ <S>(39+ recipe: (draftState: S, ...extraArgs: any[]) => S | void,40+ initialState: S41+ ): (currentState: S | void, ...extraArgs: any[]) => S;42+ // curried invocations without inital state43+ <S, A, B, C>(44+ recipe: (draftState: S, a: A, b: B, c: C) => S | void45+ ): (currentState: S, a: A, b: B, c: C) => S;46+ <S, A, B>(47+ recipe: (draftState: S, a: A, b: B) => S | void48+ ): (currentState: S, a: A, b: B) => S;49+ <S, A>(50+ recipe: (draftState: S, a: A) => S | void51+ ): (currentState: S, a: A) => S;52+ <S>(53+ recipe: (draftState: S) => S | void54+ ): (currentState: S) => S;55+ <S>(56+ recipe: (draftState: S, ...extraArgs: any[]) => S | void57+ ): (currentState: S, ...extraArgs: any[]) => S;58+}59+60+declare export var produce: IProduce61+declare export default IProduce62+63 /**4- * Immer takes a state, and runs a function against it.5- * That function can freely mutate the state, as it will create copies-on-write.6- * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.7- *8- * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe9- * any time it is called with the current state.10- *11- * @param currentState - the state to start with12- * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified13- * @param initialState - if a curried function is created and this argument was given, it will be used as fallback if the curried function is called with a state of undefined14- * @returns The next state: a new state, or the current state if nothing was modified15- */16-declare export default function produce<S>(17- currentState: S,18- recipe: (draftState: S) => S | void19-): S20-// curried invocations with inital state21-declare export default function produce<S, A, B, C>(22- recipe: (draftState: S, a: A, b: B, c: C) => S | void,23- initialState: S24-): (currentState: S | void, a: A, b: B, c: C) => S25-declare export default function produce<S, A, B>(26- recipe: (draftState: S, a: A, b: B) => S | void,27- initialState: S28-): (currentState: S | void, a: A, b: B) => S29-declare export default function produce<S, A>(30- recipe: (draftState: S, a: A) => S | void,31- initialState: S32-): (currentState: S | void, a: A) => S33-declare export default function produce<S>(34- recipe: (draftState: S) => S | void,35- initialState: S36-): (currentState: S | void) => S37-declare export default function produce<S>(38- recipe: (draftState: S, ...extraArgs: any[]) => S | void,39- initialState: S40-): (currentState: S | void, ...extraArgs: any[]) => S41-// curried invocations without inital state42-declare export default function produce<S, A, B, C>(43- recipe: (draftState: S, a: A, b: B, c: C) => S | void44-): (currentState: S, a: A, b: B, c: C) => S45-declare export default function produce<S, A, B>(46- recipe: (draftState: S, a: A, b: B) => S | void47-): (currentState: S, a: A, b: B) => S48-declare export default function produce<S, A>(49- recipe: (draftState: S, a: A) => S | void50-): (currentState: S, a: A) => S51-declare export default function produce<S>(52- recipe: (draftState: S) => S | void53-): (currentState: S) => S54-declare export default function produce<S>(55- recipe: (draftState: S, ...extraArgs: any[]) => S | void56-): (currentState: S, ...extraArgs: any[]) => S57-/**64 * Automatically freezes any state trees generated by immer.65 * This protects against accidental modifications of the state tree outside of an immer function.66 * This comes with a performance impact, so it is recommended to disable this option in production.67 * By default it is turned on during local development, and turned off in production.8 unmodified linesmodified:changelog.md+6 added
1 # Changelog2 3+### 1.4.04+5+* Improved TypeScript typings; if the base state is declared as `readonly`, the `draft` object will be upcasted to a writeable version. Fixes [#97](https://github.com/mweststrate/immer/issues/97) through [#161](https://github.com/mweststrate/immer/pull/161) by [@knpwrs](https://github.com/knpwrs)6+* It is now possible to use both `import produce from "immer"` and `import {produce} from "immer"`. Implements [#136](https://github.com/mweststrate/immer/issues/136)7+* Added several performance tests to the repository8+9 ### 1.3.110 11 * Fixed bug [#148](https://github.com/mweststrate/immer/issues/148) where original state was not always returned if the producer returned undefined and the original state was a primitive. By @stefanwille through [#157](https://github.com/mweststrate/immer/pull/157)12 155 unmodified linesmodified:package.json+3 added-2 removed
1 {2 "name": "immer",3- "version": "1.3.1",3+ "version": "1.4.0",4 "description": "Create your next immutable state by mutating the current one",5 "main": "dist/immer.js",6 "umd:main": "dist/immer.umd.js",7 "module": "dist/immer.module.js",2 unmodified lines10 "types": "./dist/immer.d.ts",11 "scripts": {12 "watch": "jest --watch",13 "test": "jest",14- "test:perf": "yarn-or-npm build && node --expose-gc node_modules/jest-cli/bin/jest.js --verbose --testRegex '__performance_tests__/.*?js$'",14+ "test:perf": "NODE_ENV=production yarn-or-npm build && cd __preformance_tests__ && babel-node add-data.js && babel-node todo.js && babel-node incremental.js",15 "test:flow": "yarn-or-npm flow check",16 "coveralls": "jest --coverage && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage",17 "build": "rimraf dist/ && cross-env NODE_ENV=production rollup -c && cpx \"src/immer.{d.ts,js.flow}\" dist",18 "prettier": "prettier \"*/**/*.js\" --ignore-path ./.prettierignore --write",48 unmodified lines67 "rollup-plugin-commonjs": "^8.2.6",68 "rollup-plugin-filesize": "^1.5.0",69 "rollup-plugin-node-resolve": "^3.0.2",70 "rollup-plugin-uglify": "^2.0.1",71+ "seamless-immutable": "^7.1.3",72 "ts-jest": "^22.4.6",73 "typescript": "^2.9.1",74 "uglify-es": "^3.3.6",75 "yarn-or-npm": "^2.0.4"29 unmodified linesmodified:readme.md+18 added-1 removed
302 unmodified lines303 const state: State = {304 x: 0;305 };306 307-const newState = produce<State>(draft => {307+const newState = produce<State>(state, draft => {308 // `x` can be modified here309 draft.x++;310 });311 5 unmodified lines317 ## Immer on older JavaScript environments?318 319 By default `produce` tries to use proxies for optimal performance. However, on older JavaScript engines `Proxy` is not available. For example, when running Microsoft Internet Explorer or React Native on Android. In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.320 321+## Importing immer322+323+`produce` is exposed as the default export, but optionally it can be used as name import as well, as this benefits some older project setups. So the following imports are all correct, where the first is recommend:324+325+```javascript326+import produce from "immer"327+import { produce } from "immer"328+329+const { produce } = require("immer")330+const produce = require("immer").produce331+const produce = require("immer").default332+333+import unleashTheMagic from "immer"334+import { produce as unleashTheMagic } from "immer"335+```336+337 ## Pitfalls338 339 1. Don't redefine draft like, `draft = myCoolNewState`. Instead, either modify the `draft` or return a new state. See [Returning data from producers](#returning-data-from-producers).340 1. Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.341 1. Immer only processes native arrays and plain objects (with a prototype of `null` or `Object`). Any other type of value will be treated verbatim! So if you modify a `Map` or `Buffer` (or whatever complex object from the draft state), the changes will be persisted. But, both in your new and old state! So, in such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.342 1. For example, working with `Date` objects is no problem, just make sure you never modify them (by using methods like `setYear` on an existing instance). Instead, always create fresh `Date` instances. Which is probably what you were unconsciously doing already.343 1. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`344 1. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.345+1. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower then `produce(base, d => { for (let x of y) d.push(x)})`346 347 ## Cool things built with immer348 349 * [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_121 unmodified linesmodified:yarn.lock+4 added
4394 unmodified lines4395 sax@^1.2.1:4396 version "1.2.4"4397 resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9"4398 4399+seamless-immutable@^7.1.3:4400+ version "7.1.3"4401+ resolved "https://registry.yarnpkg.com/seamless-immutable/-/seamless-immutable-7.1.3.tgz#d32a8a202a331dffa69e4069a367a2159252490e"4402+4403 semver-diff@^2.0.0:4404 version "2.1.0"4405 resolved "https://registry.yarnpkg.com/semver-diff/-/semver-diff-2.1.0.tgz#4bbb8437c8d37e4b0cf1a68fd726ec6d645d6d36"4406 dependencies:810 unmodified lines