map-transform
Version:
Map and transform objects with mapping definitions
33 lines • 1.6 kB
JavaScript
import { pushContext, getStateValue, setStateValue, getTargetFromState, setTargetOnState, } from '../utils/stateHelpers.js';
import { defToOperation } from '../utils/definitionHelpers.js';
import { indexOfIfArray } from '../utils/array.js';
import { noopNext } from '../utils/stateHelpers.js';
const runIterationStep = async (fn, state, value, index, target) => getStateValue(await fn(setTargetOnState({ ...state, index, value }, indexOfIfArray(target, index))));
export const iterateState = (fn) => async (state, target) => {
const values = getStateValue(state);
if (!Array.isArray(values)) {
return await runIterationStep(fn, state, values, 0, target);
}
const nextState = pushContext(state, values);
const nextValue = [];
for (const [index, value] of values.entries()) {
nextValue.push(await runIterationStep(fn, nextState, value, index, target));
}
return nextValue;
};
export default function iterate(def) {
if (!def || (typeof def === 'object' && Object.keys(def).length === 0)) {
return (_options) => (next) => async (state) => setStateValue(await next(state), undefined);
}
return (options) => {
const fn = defToOperation(def, options)(options);
return (next) => {
const runIteration = iterateState(fn(noopNext));
return async function doIterate(state) {
const nextState = await next(state);
return setStateValue(nextState, await runIteration(nextState, getTargetFromState(nextState)));
};
};
};
}
//# sourceMappingURL=iterate.js.map