index.js
This file
Path
src/index.js
48 lines · 1.8 KiB · JavaScript
Last changed by
less builds is more?Michel Weststratebefore adoption74a97b6
History of this fileTake it
One module to rule them all WIPMichel Weststratebefore adoptionb7647e4
line 1why, one step back1export {setAutoFreeze} from "./common"less builds is more?Michel Weststratebefore adoption74a97b6
line 2why, one step back2One module to rule them all WIPMichel Weststratebefore adoptionb7647e4
line 3why, one step back3import {isProxyable} from "./common"less builds is more?Michel Weststratebefore adoption74a97b6
line 4why, one step back4import {produceProxy} from "./proxy"One module to rule them all WIPMichel Weststratebefore adoptionb7647e4
lines 5–48why, one step back5import {produceEs5} from "./es5"67let useProxies = typeof Proxy !== "undefined"89/**10 * produce takes a state, and runs a function against it.11 * That function can freely mutate the state, as it will create copies-on-write.12 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned13 *14 * @export15 * @param {any} baseState - the state to start with16 * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified17 * @returns {any} a new state, or the base state if nothing was modified18 */19export default function produce(baseState, producer) {20 // curried invocation21 if (arguments.length === 1) {22 const producer = baseState23 // prettier-ignore24 if (typeof producer !== "function") throw new Error("if produce is called with 1 argument, the first argument should be a function")25 return function() {26 const args = arguments27 return produce(args[0], draft => {28 args[0] = draft // blegh!29 baseState.apply(null, args)30 })31 }32 }3334 // prettier-ignore35 {36 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)37 if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))38 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")39 }4041 return useProxies42 ? produceProxy(baseState, producer)43 : produceEs5(baseState, producer)44}4546export function setUseProxies(value) {47 useProxies = value48}