Skip to content

Instantly share code, notes, and snippets.

@phen0menon
Last active May 9, 2020 13:42
Show Gist options
  • Save phen0menon/975eb4757d0377bca15f3a8fafa080df to your computer and use it in GitHub Desktop.
Save phen0menon/975eb4757d0377bca15f3a8fafa080df to your computer and use it in GitHub Desktop.
Reducer helper for convenient reducer creation
export interface Action {
type: string;
}
export type CreateReducerReducer<S, A> = (state: S, action: A) => S;
export type CreateReducerComponents<S, A> = Record<
string,
CreateReducerReducer<S, A>
>;
export const createReducer = <S, A extends Action>(
components: CreateReducerComponents<S, A>,
initialState: S
) => (state: S = initialState, action: A) =>
components.hasOwnProperty(action.type)
? components[action.type](state, action)
: state;
/*
Usage:
export const someReducer = createReducer<State, Action>(
{
[ActionTypes.SOME_ACTION]: (state, action) => {
// ...
}
},
initialState
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment