Last active
May 7, 2019 06:49
-
-
Save einatbar/8cd93a167aeb6d609ceb93787230dbdf to your computer and use it in GitHub Desktop.
Simple Redux implementation - final
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
| const createStore = (reducer, initialState = {}, middlewares = []) => { | |
| let state = initialState; | |
| const listeners = []; | |
| // final step - call the reducer and invoke the listeners | |
| let finalMiddleware = (action) => { | |
| state = reducer(state, action); | |
| listeners.forEach(listener => listener()); | |
| return state; | |
| } | |
| // the middleware API is constructed of getState and dispatch | |
| const middlewareAPI = { getState: () => state, dispatch: (action) => finalMiddleware(action) } | |
| // evalutate the first function in the structure of the middlewares | |
| const newMiddleWares = middlewares.map(middleware => middleware(middlewareAPI)); | |
| // go over the new middlewares reversed and evaluate the second function in the structure | |
| // the second function receives the third fucntion of the next middleware | |
| // this way we can make sure that when the developer will call next(action) | |
| // he will acually execute the next middleware's most inner funciton | |
| for(let i = newMiddleWares.length - 1; i >= 0; i--) { | |
| finalMiddleware = newMiddleWares[i](finalMiddleware); | |
| } | |
| return { | |
| ...middlewareAPI, | |
| subscribe: (listener) => { | |
| listeners.push(listener); | |
| return () => {listeners.splice(listeners.indexOf(listener), 1);}} | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment