UNPKG

map-transform

Version:

Map and transform objects with mapping definitions

47 lines 2.24 kB
import mapAny from 'map-any/async.js'; import { pathGetter } from '../operations/getSet.js'; import { getStateValue, setStateValue, goForward, revFromState, } from '../utils/stateHelpers.js'; import { defToOperation } from '../utils/definitionHelpers.js'; import { noopNext } from '../utils/stateHelpers.js'; import { isObject } from '../utils/is.js'; const FLATTEN_DEPTH = 1; const flattenIfArray = (data) => Array.isArray(data) ? data.flat(FLATTEN_DEPTH) : data; const findAllMatches = (value, state, arr, getProp) => arr.filter((val) => getProp(val, state) === value); const findOneMatch = (value, state, arr, getProp) => arr.find((val) => getProp(val, state) === value); const matchInArray = (getArray, match, getProp) => (state) => { const getFn = getArray({})(noopNext); return async (value) => { const { value: arr } = await getFn(goForward(state)); if (Array.isArray(arr)) { return match(value, state, arr, getProp); } else if (isObject(arr)) { return match(value, state, [arr], getProp); } else { return undefined; } }; }; export function lookup({ arrayPath, propPath, matchSeveral = false, flip = false, }) { return (options) => { if (typeof propPath !== 'string' && propPath !== undefined) { throw new TypeError("The 'lookup' operation does not allow `path` (the prop path) to be a pipeline"); } const getter = pathGetter(propPath); const matchFn = matchInArray(defToOperation(arrayPath, options), matchSeveral ? findAllMatches : findOneMatch, getter); const extractProp = (state) => async (value) => getter(value, state); return (next) => async function doLookup(state) { const nextState = await next(state); const value = getStateValue(nextState); const rev = revFromState(state, flip); const matcher = rev ? extractProp : matchFn; const matches = await mapAny(matcher(nextState), value); return setStateValue(nextState, flattenIfArray(matches)); }; }; } export function lookdown(props) { return lookup({ ...props, flip: !props.flip }); } //# sourceMappingURL=lookup.js.map