Skip to content

Commit beaac62

Browse files
committed
support initialState
1 parent 9654444 commit beaac62

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

src/index.js

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,19 @@
1-
export default (...reducers) => (prevState, value, ...args) =>
2-
reducers.reduce(
3-
(newState, reducer) => reducer(newState, value, ...args),
4-
prevState
5-
);
1+
export default (...args) => {
2+
const initialState =
3+
typeof args[args.length - 1] !== 'function' && args.pop();
4+
const reducers = args;
5+
6+
if (typeof initialState === 'undefined') {
7+
throw new TypeError(
8+
'The initial state may not be undefined. If you do not want to set a value for this reducer, you can use null instead of undefined.'
9+
);
10+
}
11+
12+
return (prevState, value, ...args) =>
13+
typeof prevState === 'undefined'
14+
? initialState
15+
: reducers.reduce(
16+
(newState, reducer) => reducer(newState, value, ...args),
17+
prevState
18+
);
19+
};

test/index.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,24 @@
11
import reduceReducers from '../src';
22

3+
test('returns initialState', () => {
4+
const initialState = { A: 0, B: 0 };
5+
const reducer = reduceReducers(
6+
(state, payload) => ({
7+
...state,
8+
A: state.A + payload
9+
}),
10+
initialState
11+
);
12+
13+
expect(reducer()).toEqual(initialState);
14+
});
15+
16+
test('throws an error if initialState is undefined', () => {
17+
expect(() => {
18+
reduceReducers(undefined);
19+
}).toThrow();
20+
});
21+
322
test('combines multiple reducers into a single reducer', () => {
423
const reducer = reduceReducers(
524
(state, payload) => ({ ...state, A: state.A + payload }),

0 commit comments

Comments
 (0)