Last active
January 13, 2022 04:04
-
-
Save Goku-kun/00deacd5cec0bb968000e35a3e427ec3 to your computer and use it in GitHub Desktop.
This gist is a very stripped out implementation of the redux library.
This file contains 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
function createStore(reducer) { | |
let state; | |
let subscribers = []; | |
function getState() { | |
return state; | |
} | |
function dispatch(action) { | |
state = reducer(state, action); | |
//update the state and then call each of the subscriber. | |
subscribers.forEach((subscriber) => subscriber()); | |
} | |
function subscribe(subscriber) { | |
subscribers.push(subscriber); | |
// function to unsubscribe a particular subscribed function. | |
return function () { | |
subscribers = subscribers.filter(function (itemSubscriber) { | |
return subscriber !== itemSubscriber; | |
}); | |
}; | |
} | |
function replaceReducer(newReducer) { | |
// replace the original reducer | |
reducer = newReducer; | |
} | |
// this call to dispatch is made to initialize the state object because reducer would contain a default initial state. | |
dispatch({}); | |
return { getState, dispatch, subscribe, replaceReducer }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment