Skip to content
Myr

index.js

This file

Path

src/index.js

42 lines · 1.7 KiB · JavaScript

Last changed by

Merge pull request #69 from mweststrate/feature/fast-pruneMichel Weststratebefore adoptione28bf2a

History of this file

Take it

Merge pull request #69 from mweststrate/feature/fast-pruneMichel Weststratebefore adoptione28bf2a

line 1why, one step back
1export {setAutoFreeze, setUseProxies} from "./common"

Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0

line 2why, one step back
2

Merge pull request #69 from mweststrate/feature/fast-pruneMichel Weststratebefore adoptione28bf2a

line 3why, one step back
3import {isProxyable, getUseProxies} from "./common"

Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0

lines 4–38why, one step back
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 baseState.apply(null, 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 }38

Merge pull request #69 from mweststrate/feature/fast-pruneMichel Weststratebefore adoptione28bf2a

line 39why, one step back
39 return getUseProxies()

Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0

lines 40–42why, one step back
40 ? produceProxy(baseState, producer)
41 : produceEs5(baseState, producer)42}