-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleRedux.js
50 lines (45 loc) · 1.38 KB
/
SimpleRedux.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
function createStore(reducer, enhancer) {
if (enhancer) {
return enhancer(createStore)(reducer); // when given applyMiddleware
}
let state = undefined; // store state tree
const listeners = [];
dispatch({ type: "@@redux/INIT" }); // dispatch init event to set state
function dispatch(action) {
state = reducer(state, action);
listeners.forEach((listener) => listener());
}
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
listeners.splice(listeners.indexOf(listener), 1);
};
}
function getState() {
return state;
}
return { dispatch, subscribe, getState };
}
function combineReducers(reducers) {
return function reducer(state = {}, action) {
const newState = {};
for (const key in reducers) {
// iterate keys and calculate new state
newState[key] = reducers[key](state[key], action);
}
return newState;
};
}
function applyMiddleware(...middlewares) {
return (createStore) => (reducer, ...args) => {
const store = createStore(reducer, ...args);
middlewares = middlewares.slice().reverse();
let dispatch = store.dispatch;
// wrapper dispatch by middlewares
middlewares.forEach(
(middleware) => (dispatch = middleware(store)(dispatch))
);
return { ...store, dispatch };
};
}
const SimpleRedux = { createStore, combineReducers, applyMiddleware };