UNPKG

map-transform

Version:

Map and transform objects with mapping definitions

48 lines 1.74 kB
import deepmerge from 'deepmerge'; import { getStateValue, setStateValue, isNonvalueState, } from '../utils/stateHelpers.js'; import { defToOperation } from '../utils/definitionHelpers.js'; import { isObject } from '../utils/is.js'; export function mergeExisting(target, source) { if (Array.isArray(target)) { const arr = source.slice(); target.forEach((value, index) => { arr[index] = deepmerge(source[index], value, { arrayMerge: mergeExisting, }); }); return arr; } return target; } export function mergeStates(state, thisState) { const target = getStateValue(state); const source = getStateValue(thisState); const value = !isObject(source) ? target : !isObject(target) ? source : deepmerge(target, source, { arrayMerge: mergeExisting }); return setStateValue(state, value); } export default function merge(...defs) { return (options) => (next) => { if (defs.length === 0) { return async (state) => setStateValue(await next(state), undefined); } const pipelines = defs.map((def) => defToOperation(def, options)(options)(next)); return async function (state) { const nextState = await next(state); if (isNonvalueState(nextState, options.nonvalues)) { return setStateValue(nextState, undefined); } else { const states = []; for (const pipeline of pipelines) { states.push(await pipeline(nextState)); } return states.reduce(mergeStates); } }; }; } //# sourceMappingURL=merge.js.map