export type State = Readonly < Object > ; export type Action = { type : string ; payload : any ; } ; export type Reducer < S extends State , A extends Action > = ( s : S , a : A ) => S ; type Listener < S extends State > = ( ns : S , ps ? : S ) => void ; type Unsubscribe = ( ) => void ; export interface Store < S extends State , A extends Action > { dispatch : ( a : A ) => void ; getState : ( ) => S ; subscribe : ( listener : Listener < S > ) => Unsubscribe ; } param preloadedState param reducer returns function createStore < S extends State , A extends Action > ( preloadedState , reducer ) { const listeners = [ ] ; let currentState = preloadedState ; const dispatch = ( action ) => { const nextState = reducer ( currentState , action ) ; const prevState = currentState ; currentState = nextState ; for ( const cb of listeners ) { cb ( currentState , prevState ) ; } } ; const subscribe = ( listener ) => { let isSubscribed = true ; listeners . push ( listener ) ; return ( ) => { if ( ! isSubscribed ) { return ; } const index = listeners . indexOf ( listener ) ; listeners . splice ( index , 1 ) ; isSubscribed = false ; } ; } ; const getState = ( ) => { return currentState ; } ; return { dispatch , getState , subscribe , } ; } export default createStore ;