Created
May 15, 2019 11:33
-
-
Save kasperpeulen/a986ca942fcd065b117d26afe8935d32 to your computer and use it in GitHub Desktop.
The essence of redux in 30 lines of code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.