updux/dist/reducer.js

33 lines
1.4 KiB
JavaScript
Raw Normal View History

2025-01-31 18:16:41 +00:00
import * as R from 'remeda';
import u from '@yanick/updeep-remeda';
import { D } from '@mobily/ts-belt';
export function buildReducer(initialStateState, mutations = [], defaultMutation, subduxes = {}, inheritedReducer) {
const subReducers = D.map(subduxes, D.getUnsafe('reducer'));
const reducer = (state = initialStateState, action) => {
if (!(action === null || action === void 0 ? void 0 : action.type))
throw new Error('reducer called with a bad action');
let active = mutations.filter(({ matcher }) => matcher(action));
if (active.length === 0 && defaultMutation)
active.push(defaultMutation);
if (!active.some(R.prop('terminal')) && inheritedReducer) {
active.push({
mutation: (_payload, action) => (state) => {
return u(state, inheritedReducer(state, action));
},
});
}
if (!active.some(R.prop('terminal')) &&
D.values(subReducers).length > 0) {
active.push({
mutation: (payload, action) => (state) => {
return u(state, R.mapValues(subReducers, (reducer, slice) => (state) => {
return reducer(state, action);
}));
},
});
}
return active.reduce((state, { mutation }) => mutation(action.payload, action)(state), state);
};
return reducer;
}