Skip to content

Instantly share code, notes, and snippets.

@kasperpeulen
Created May 15, 2019 11:33
Show Gist options
  • Save kasperpeulen/a986ca942fcd065b117d26afe8935d32 to your computer and use it in GitHub Desktop.
Save kasperpeulen/a986ca942fcd065b117d26afe8935d32 to your computer and use it in GitHub Desktop.
The essence of redux in 30 lines of code.
class Store<S> {
private readonly reducer: (state: S, action: Action) => S;
private state: S;
private listeners: Listener[] = [];
constructor(reducer, state) {
this.reducer = reducer;
this.state = state;
}
getState(): S {
return this.state;
}
dispatch(action: Action): void {
this.state = this.reducer(this.state, action);
this.listeners.forEach(it => it());
}
subscribe(listener: Listener): Unsubscribe {
this.listeners = [...this.listeners, listener];
return () => {
this.listeners = this.listeners.filter(it => it !== listener);
};
}
}
type Action = { type: string; payload: any };
type Listener = () => void;
type Unsubscribe = () => void;
@jordrake
Copy link

Your listeners should be provided this.state on line 17.

@deenem
Copy link

deenem commented Oct 18, 2019

Rather than having the reducer passed into the constructor, would it make sense to have a reducers array and an addReducer(s) and removeReducer(s) function?
It just seems unlikely that a complex system would only ever have one, fixed reducer function for the entire State. More likely that modules would want to add reducers to modify state when they are instantiated, then remove their reducers when they were done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment