Skip to content

Instantly share code, notes, and snippets.

@tomtheisen
Created July 1, 2020 05:57
Show Gist options
  • Save tomtheisen/f6b87d79da03f2e6ce0731a4798e6894 to your computer and use it in GitHub Desktop.
Save tomtheisen/f6b87d79da03f2e6ce0731a4798e6894 to your computer and use it in GitHub Desktop.
The Last Reducer You'll Ever Need
interface UniversalAction<TState> {
type: "UNIVERSAL";
map: (previous: TState) => TState;
}
function universalAction<TState>(map: (previous: TState) => TState): UniversalAction<TState> {
return { type: "UNIVERSAL", map };
}
// all other reducers are now redundant
function universalReducer<TState>(previous: TState, action: UniversalAction<TState>) {
switch (action.type) {
case "UNIVERSAL": return action.map(previous);
default: throw "Obsolete action type detected";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment