resolve #111: allow passing initial state to curried producer function
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Patrick Kerschbaum · committed by Patrick Kerschbaum · parent 77c17f7 · Browse files · 5 files·+80 added−33 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+80 added−33 removed
- tests:+16 added−4 removed
- other:+64 added−29 removed
Provenance
- Commit
202d54c- Tree
7e68751- Author
Patrick Kerschbaum <patrick.kerschbaum@gmail.com>- Committer
Patrick Kerschbaum <patrick.kerschbaum@gmail.com>- Parent
77c17f7
5 files changed+80 added−33 removed
modified:__tests__/curry.js+16 added-4 removed
8 unmodified lines910111213141513141516171819202421222324252627282920 unmodified lines5051525354555657585960616263646566678 unmodified lines setUseProxies(useProxies)
it("should check arguments", () => { expect(() => produce()).toThrow(/produce expects 1 or 2 arguments/) expect(() => produce(() => {}, {})).toThrow( /the second argument to produce should be a function/ ) expect(() => produce(new Buffer(""), () => {})).toThrow( /the first argument to an immer producer should be a primitive, plain object or array/ ) expect(() => produce({}, () => {}, [])).toThrow( /produce expects 1 or 2 arguments/ ) expect(() => produce({}, {})).toThrow(/should be a function/) expect(() => produce({})).toThrow( /first argument should be a function/ /if first argument is not a function, the second argument to produce should be a function/ ) expect(() => produce(() => {}, () => {})).toThrow( /if first argument is a function .* the second argument to produce cannot be a function/ ) })
it("should support currying", () => { const state = [{}, {}, {}]20 unmodified lines
expect(reducer(undefined, 3)).toEqual({hello: "world"}) expect(reducer({}, 3)).toEqual({index: 3}) })
it("should support passing an initial state as second argument", () => { const reducer = produce( (item, index) => { item.index = index }, {hello: "world"} )
expect(reducer(undefined, 3)).toEqual({hello: "world", index: 3}) expect(reducer({}, 3)).toEqual({index: 3}) }) })}modified:src/immer.d.ts+13 added-8 removed
12344567678910101112131415161718191920212223222425262725282930312832333435363711 unmodified lines/** * Immer takes a state, and runs a function against it. * That function can freely mutate the state, as it will create copies-on-write. * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned. * * If only one argument is passed, this is interpreted as the recipe, and will create a curried function that will execute the recipe * any time it is called with a base state * If the first argument is a function, this is interpreted as the recipe, and will create a curried function that will execute the recipe * any time it is called with the current state. * * @param currentState - the state to start with * @param thunk - function that receives a proxy of the current state as first argument and which can be freely modified * @param recipe - function that receives a proxy of the current state as first argument and which can be freely modified * @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 undefined * @returns The next state: a new state, or the current state if nothing was modified */export default function<S = any>( currentState: S, recipe: (this: S, draftState: S) => void): S// curried invocationsexport default function<S = any>( recipe: (this: S, draftState: S, ...extraArgs: any[]) => void recipe: (this: S, draftState: S, ...extraArgs: any[]) => void, initialState?: S): (currentState: S, ...extraArgs: any[]) => Sexport default function<S = any, A = any>( recipe: (this: S, draftState: S, a: A) => void recipe: (this: S, draftState: S, a: A) => void, initialState?: S): (currentState: S, a: A) => Sexport default function<S = any, A = any, B = any>( recipe: (this: S, draftState: S, a: A, b: B) => void recipe: (this: S, draftState: S, a: A, b: B) => void, initialState?: S): (currentState: S, a: A, b: B) => Sexport default function<S = any, A = any, B = any, C = any>( recipe: (this: S, draftState: S, a: A, b: B, c: C) => void recipe: (this: S, draftState: S, a: A, b: B, c: C) => void, initialState?: S): (currentState: S, a: A, b: B, c: C) => S
/** * Automatically freezes any state trees generated by immer.11 unmodified linesmodified:src/immer.js+18 added-7 removed
13 unmodified lines14151617181920211920222322242526272829303132333435362537382739404142434445343546474849509 unmodified lines13 unmodified lines * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified * @returns {any} a new state, or the base state if nothing was modified */export default function produce(baseState, producer) { // prettier-ignore if (arguments.length !== 1 && arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)
// curried invocation if (arguments.length === 1) { const producer = baseState if (typeof baseState === "function") { // prettier-ignore if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function") if (typeof producer === "function") throw new Error("if first argument is a function (curried invocation), the second argument to produce cannot be a function")
const initialState = producer const recipe = baseState
return function() { const args = arguments
const currentState = args[0] === undefined && initialState !== undefined ? initialState : args[0]
return produce(args[0], draft => { return produce(currentState, draft => { args[0] = draft // blegh! return producer.apply(draft, args) return recipe.apply(draft, args) }) } }
// prettier-ignore { if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length) if (typeof producer !== "function") throw new Error("the second argument to produce should be a function") if (typeof producer !== "function") throw new Error("if first argument is not a function, the second argument to produce should be a function") }
// if state is a primitive, don't bother proxying at all and just return whatever the producer returns on that value if (typeof baseState !== "object" || baseState === null)9 unmodified linesmodified:src/immer.js.flow+13 added-8 removed
1 unmodified line2 3 /**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 returned6+ * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned.7 *8- * If only one argument is passed, this is interpreted as the recipe, and will create a curried function that will execute the recipe9- * any time it is called with a base state8+ * 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 thunk - function that receives a proxy of the current state as first argument and which can be freely modified12+ * @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) => void19 ): S20 // curried invocations21 declare export default function produce<S, A, B, C>(21- recipe: (draftState: S, a: A, b: B, c: C) => void22+ recipe: (draftState: S, a: A, b: B, c: C) => void,23+ initialState?: S24 ): (currentState: S, a: A, b: B, c: C) => S25 declare export default function produce<S, A, B>(24- recipe: (draftState: S, a: A, b: B) => void26+ recipe: (draftState: S, a: A, b: B) => void,27+ initialState?: S28 ): (currentState: S, a: A, b: B) => S29 declare export default function produce<S, A>(27- recipe: (draftState: S, a: A) => void30+ recipe: (draftState: S, a: A) => void,31+ initialState?: S32 ): (currentState: S) => S33 declare export default function produce<S>(30- recipe: (draftState: S, ...extraArgs: any[]) => void34+ recipe: (draftState: S, ...extraArgs: any[]) => void,35+ initialState?: S36 ): (currentState: S, ...extraArgs: any[]) => S37 38 /**39 * Automatically freezes any state trees generated by immer.11 unmodified linesmodified:readme.md+20 added-6 removed
34 unmodified lines35 The Immer package exposes a default function that does all the work.36 37 `produce(currentState, producer: (draftState) => void): nextState`38 39-There is also a curried overload that is explained [below](#currying)39+There is also a curried overload that is explained [below](#currying).40 41 ## Example42 43 ```javascript123 unmodified lines167 ```168 169 ## Currying170 171-`produce` can be called with one or two arguments.172-The one argument version is intended to be used for currying. This means that you get a pre-bound producer that only needs a state to produce the value from.171+Passing a function as the first argument to `produce` is intended to be used for currying. This means that you get a pre-bound producer that only needs a state to produce the value from.172 The producer function gets passed in the draft, and any further arguments that were passed to the curried function.173 174 For example:175 24 unmodified lines200 })201 ```202 203 Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).205-One think to keep in mind; you cannot use this construction to initialize an uninitialized state. E.g. `draft = {}` doesn't do anything useful.204 205+If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:206+207+```javascript208+import produce from 'immer'209+210+const byId = produce((draft, action) => {211+ switch (action.type) {212+ case RECEIVE_PRODUCTS:213+ action.products.forEach(product => {214+ draft[product.id] = product215+ })216+ })217+ }218+}, { 1: { id: 1, name: "product-1" } })219+```220+221 ## Auto freezing222 223 Immer automatically freezes any state trees that are modified using `produce`.224 This protects against accidental modifications of the state tree outside of a producer.4 unmodified lines229 230 ## Returning data from producers231 232 It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway.219-However, it allowed to just `return draft`.233+However, it is allowed to just `return draft`.234 221-It is also allowed to return abritrarily other data from the producer function. But _only_ if you didn't modify the draft.235+It is also allowed to return arbitrarily other data from the producer function. But _only_ if you didn't modify the draft.236 This can be useful to produce an entirely new state. Some examples:237 238 ```javascript239 const userReducer = produce((draft, action) => {194 unmodified lines