Skip to content

Instantly share code, notes, and snippets.

@baransu
Created August 24, 2016 14:08
Show Gist options
  • Save baransu/b34002649128f7ce17536ff71ace29b2 to your computer and use it in GitHub Desktop.
Save baransu/b34002649128f7ce17536ff71ace29b2 to your computer and use it in GitHub Desktop.
export function createReducer(initialState, handlers) {
const match = (key, type) => (
key
.replace(/ /g, '')
.split(',')
.reduce((acc, k) => (
acc || type.indexOf(k) > -1 ? k : null
), null)
);
const matchKey = (keys, type) => (
keys.indexOf(type) > -1 && type
|| keys.reduce((acc, key) => (
key.indexOf(",") > -1 && match(key, type) || acc
), null)
|| (keys.indexOf("_") > -1 && "_") || ""
);
return function reducer(state = initialState, action) {
const matchedKey = matchKey(Object.keys(handlers), action.type);
return handlers.hasOwnProperty(matchedKey) ? handlers[matchedKey](state, action) : state;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment