Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function createStore(reducer, initState, enhancer) {
- if (typeof initState == "function" && enhancer == null) {
- enhancer = initState;
- initState = undefined;
- }
- if (enhancer !== undefined) {
- return enhancer(createStore)(reducer, initState);
- }
- let currentReducer = reducer;
- let currentState = initState;
- let currentListeners = [];
- let nextListeners = currentListeners;
- function dispatch(action) {
- currentState = currentReducer(currentState, action);
- if (currentListeners !== nextListeners) {
- currentListeners = nextListeners;
- }
- for (let i = 0; i < currentListeners.length; i++) {
- const fn = currentListeners[i];
- fn();
- }
- }
- function replaceReducer(nextReducer) {
- currentReducer = nextReducer;
- }
- function subscribe(callback) {
- if (nextListeners === currentListeners) {
- nextListeners = currentListeners.slice();
- }
- nextListeners.push(callback);
- return function unsubscribe() {
- if (nextListeners === currentListeners) {
- nextListeners = currentListeners.slice();
- }
- if (nextListeners.indexOf(callback) > -1) {
- nextListeners.splice(nextListeners.indexOf(callback), 1);
- }
- };
- }
- function getState() {
- return currentState;
- }
- let store = {
- subscribe,
- getState,
- dispatch,
- replaceReducer
- };
- store.dispatch({
- type: "INIT"
- });
- return store;
- }
- function applyMiddleware(...middlewares) {
- return createStore => (...args) => {
- const store = createStore(...args);
- let dispatch;
- const middlewareAPI = {
- getState: store.getState,
- dispatch: (...args) => dispatch(...args)
- };
- const chain = middlewares.map(middleware => middleware(middlewareAPI));
- dispatch = compose(...chain)(store.dispatch);
- return {
- ...store,
- dispatch
- };
- };
- }
- function compose(...fns) {
- if (fns.length === 0) {
- return arg => arg;
- }
- if (fns.length === 1) {
- return fns[0];
- }
- return fns.reduce((a, b) => (...args) => a(b(...args)));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement