splat mutation

This commit is contained in:
Yanick Champoux 2022-09-02 10:40:34 -04:00
parent 23724931e9
commit dd0dda0970
4 changed files with 29 additions and 8 deletions

View File

@ -8,7 +8,7 @@
"updeep": "^1.2.1"
},
"license": "MIT",
"main": "dist/index.js",
"main": "src/index.js",
"name": "updux",
"description": "Updeep-friendly Redux helper framework",
"scripts": {

View File

@ -126,11 +126,11 @@ export class Updux {
action = action.type;
}
if (!this.#actions[action]) {
if (!this.#actions[action] && action !== '*') {
throw new Error(`action '${action}' is not defined`);
}
if( terminal ) {
if (terminal) {
const originalMutation = mutation;
mutation = (...args) => originalMutation(...args);
mutation.terminal = true;

View File

@ -71,3 +71,20 @@ test('strings and generators', async () => {
expect(foo.actions.d).toBeTypeOf('function');
});
test('splat mutation', () => {
const myDux = new Updux({
initial: [],
actions: { one: null, two: null },
mutations: {
'*': (payload) => (state) => payload ? [...state, payload] : state,
},
});
const store = myDux.createStore();
expect(store.getState()).toEqual([]);
store.dispatch.one(11);
store.dispatch.two(22);
expect(store.getState()).toEqual([11, 22]);
});

View File

@ -4,9 +4,13 @@ import u from 'updeep';
const localMutation = (mutations) => (action) => (state) => {
const mutation = mutations[action.type];
if (!mutation) return state;
const splatMutation = mutations['*'];
return mutation(action.payload, action)(state);
if (mutation) state = mutation(action.payload, action)(state);
if (splatMutation) state = splatMutation(action.payload, action)(state);
return state;
};
const subMutations = (subduxes) => (action) => (state) => {
@ -28,7 +32,7 @@ const subMutations = (subduxes) => (action) => (state) => {
export function buildUpreducer(mutations, subduxes) {
return (action) => (state) => {
if( ! mutations[action.type]?.terminal )
if (!mutations[action.type]?.terminal)
state = subMutations(subduxes)(action)(state);
return localMutation(mutations)(action)(state);