Skip to content

Instantly share code, notes, and snippets.

@theshock
Created April 29, 2016 10:11
Show Gist options
  • Save theshock/35b78fcd9dac84ec6afa1d78bdca1f1e to your computer and use it in GitHub Desktop.
Save theshock/35b78fcd9dac84ec6afa1d78bdca1f1e to your computer and use it in GitHub Desktop.
import _ from 'lodash-fp';
import { createFunctionsChain, groupProperties } from 'utils/collection';
export default function createStoreSection(prefix, samples) {
if (samples.some(sample => !sample)) {
throw new TypeError('Sample cant be empty');
}
const path = (suffix) => `${prefix}/${suffix}`;
const reducersSource = groupProperties( _.map('reducers', samples) );
const initialState = samples.reduce(
(state, sample) => ({ ...state, ...sample.initialState }), {}
);
const reducersMap = Object.keys(reducersSource)
.reduce((result, key) => {
result[path(key)] = createFunctionsChain(reducersSource[key]);
return result;
}, {});
const payload = (actionName, args) => {
return samples.reduce( (result, value) =>
value.payloads && value.payloads[actionName]
? { ...result, ...value.payloads[actionName](args, initialState) }
: result
, {});
};
const createAction = (actionName, args) => ({
type: path(actionName),
payload: payload(actionName, args)
});
return { initialState, reducersMap, createAction };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment