splat mutation

typescript
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

@ -107,8 +107,8 @@ export class Updux {
* updux if not already present (the idea being that making a typo on a string
* is easy, but passing a wrong function very more unlikely).
* @param {Function} mutation - Mutating function.
* @param {bool} terminal - If true, subduxes' mutations won't be invoked on
* the action.
* @param {bool} terminal - If true, subduxes' mutations won't be invoked on
* the action.
* @return {void}
*/
setMutation(action, mutation, terminal = false) {
@ -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);