immer.js
This file
Path
src/immer.js
48 lines · 2.0 KiB · JavaScript
Last changed by
Merge pull request #113 from christiangenco/patch-1benbraoubefore adoption233e1d3
History of this fileTake it
Renamed `index.js` -> `immer.js`Michel Weststratebefore adoptionc4f5667
lines 1–26why, one step back1export {setAutoFreeze, setUseProxies} from "./common"23import {isProxyable, getUseProxies} from "./common"4import {produceProxy} from "./proxy"5import {produceEs5} from "./es5"67/**8 * produce takes a state, and runs a function against it.9 * That function can freely mutate the state, as it will create copies-on-write.10 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned11 *12 * @export13 * @param {any} baseState - the state to start with14 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified15 * @returns {any} a new state, or the base state if nothing was modified16 */17export default function produce(baseState, producer) {18 // curried invocation19 if (arguments.length === 1) {20 const producer = baseState21 // prettier-ignore22 if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function")23 return function() {24 const args = arguments25 return produce(args[0], draft => {26 args[0] = draft // blegh!Fixed #105: Curried reducers not returning new statesMichel Weststratebefore adoptionc850b2f
line 27why, one step back27 return producer.apply(draft, args)Renamed `index.js` -> `immer.js`Michel Weststratebefore adoptionc4f5667
lines 28–37why, one step back28 })29 }30 }3132 // prettier-ignore33 {34 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)35 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")36 }37Merge pull request #113 from christiangenco/patch-1benbraoubefore adoption233e1d3
line 38why, one step back38 // if state is a primitive, don't bother proxying at all and just return whatever the producer returns on that valueImplemented and document #108: allow returning values from producersMichel Weststratebefore adoptionc589ddd
lines 39–44why, one step back39 if (typeof baseState !== "object" || baseState === null)40 return producer(baseState)41 if (!isProxyable(baseState))42 throw new Error(43 `the first argument to an immer producer should be a primitive, plain object or array, got ${typeof baseState}: "${baseState}"`44 )Renamed `index.js` -> `immer.js`Michel Weststratebefore adoptionc4f5667
lines 45–48why, one step back45 return getUseProxies()46 ? produceProxy(baseState, producer)47 : produceEs5(baseState, producer)48}