Skip to content
Myr

immer.js

This file

Path

src/immer.js

42 lines · 1.7 KiB · JavaScript

Last changed by

Renamed `index.js` -> `immer.js`Michel Weststratebefore adoptionc4f5667

History of this file

Take it

Renamed `index.js` -> `immer.js`Michel Weststratebefore adoptionc4f5667

lines 1–42why, one step back
1export {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!27 producer.apply(draft, args)28 })29 }30 }3132 // prettier-ignore33 {34 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)35 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))36 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")37 }3839 return getUseProxies()40 ? produceProxy(baseState, producer)41 : produceEs5(baseState, producer)42}