-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcombineReducer.js
47 lines (38 loc) · 1.39 KB
/
combineReducer.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
import { ActionTypes } from "./createStore.js"
/**
* @param {Object} reducers as object
* @returns {Fucntion} a combined functions of reducers
*/
const combineReducers = (reducers) => {
const finalReducers = Object.keys(reducers)
// check the reducer shape
assertReducerShape(reducers)
return function combination(state,action){
let newStoreState = {};
let hasChanged = false
for (let index = 0; index < finalReducers.length; index++) {
const key = finalReducers[index]
const reducer = reducers[key];
const prevState = state ? state[key] : undefined
const nextState = reducer(prevState,action)
newStoreState[key] = nextState
hasChanged = hasChanged || nextState !== prevState
}
hasChanged = hasChanged || finalReducers.length !== Object.keys(state).length
return hasChanged ? newStoreState : state
}
}
/**
* @param {Array} reducers
* Basically its checks all the reducers shape
*/
const assertReducerShape = (reducers) => {
Object.keys(reducers).forEach(key => {
const reducer = reducers[key]
const initialState = reducer(undefined,{type: ActionTypes.UNKNOWN})
if(initialState === undefined){
throw new Error("GOT INITIAL STATE AS UNDEFINED DURING INITIALIZATION FROM REDUCER")
}
})
}
export default combineReducers