Skip to content

Instantly share code, notes, and snippets.

@g4rcez
Last active October 11, 2019 02:45
Show Gist options
  • Save g4rcez/4005a4258842d3543ee1663b28c79108 to your computer and use it in GitHub Desktop.
Save g4rcez/4005a4258842d3543ee1663b28c79108 to your computer and use it in GitHub Desktop.
Simple function to create reducer with [key:string]: () => {
type Action = {
// tslint:disable-next-line: no-reserved-keywords
readonly type: string;
readonly [key: string]: any;
};
export type State = { readonly [key: string]: any } & Object;
type Cases<T> = {
[key: string]: (state: T, action: any) => any;
};
const possibleErrors = (initialState: State, cases: Cases<any>) => {
if (initialState === undefined) {
throw new Error("initialState should not be undefined");
}
if (Object.prototype.toString.call(cases) !== "[object Object]") {
throw new Error("CreateReducer expects the second argument as an object representing reducer");
}
};
const CreateReducer = <T>(initialState: State, cases: Cases<T>) => {
possibleErrors(initialState, cases);
return (state: State = initialState, action: Action): State => {
if (cases.hasOwnProperty(action.type)) {
return cases[action.type](state as T, action);
}
return state;
};
};
export default CreateReducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment