Skip to content

Instantly share code, notes, and snippets.

@patrixr
Last active August 17, 2019 03:47
Show Gist options
  • Save patrixr/aed62eba2034d4930c3444ab2bba622a to your computer and use it in GitHub Desktop.
Save patrixr/aed62eba2034d4930c3444ab2bba622a to your computer and use it in GitHub Desktop.
Experimental Redux Mutation Wrapper
import _ from 'lodash';
const ALLOWED_MUTATIONS = {
set(key) {
return (state, action) => ({ [key]: action[key] })
},
increment(key) {
return state => ({ [key]: state[key] + 1 });
},
decrement(key) {
return state => ({ [key]: state[key] - 1 });
},
updateLoading() {
return state => ({ loading: state.requestCount > 0 });
}
};
/**
* Experimental mutation wrapper with a chainable api
*
* e.g Usage
* let fn = m.set('users').andThen.increment('userCount')
*
* fn(state, action) => returns the changes to apply to the state
*
*
* @export
* @param {*} [muts=[]]
* @returns
*/
export default function Mutation(muts = []) {
let mutationWrapper = function (state, action) {
let changes = {};
_.chain(muts)
.map(fn => fn(state, action))
.each(change => _.extend(changes, change));
return changes;
}
_.each(ALLOWED_MUTATIONS, (mut, key) => {
mutationWrapper[key] = (...params) => {
// Build a fresh wrapper with the added mutation
return Mutation([ ...muts, mut(...params) ]);
}
});
mutationWrapper.andThen = mutationWrapper;
mutationWrapper.and = mutationWrapper;
return mutationWrapper;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment