Skip to content

Commit

Permalink
pass initial state when state is undefined and value defined
Browse files Browse the repository at this point in the history
  • Loading branch information
timche committed Jul 19, 2018
1 parent f97f93e commit 12dc762
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
22 changes: 15 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,19 @@ export default (...args) => {
);
}

return (prevState, value, ...args) =>
typeof (prevState === 'undefined') && initialState
? initialState
: reducers.reduce(
(newState, reducer) => reducer(newState, value, ...args),
prevState
);
return (prevState, value, ...args) => {
const prevStateIsUndefined = typeof (prevState === 'undefined');
const valueIsUndefined = typeof value === 'undefined';

if (prevStateIsUndefined && valueIsUndefined && initialState) {
return initialState;
}

return reducers.reduce(
(newState, reducer) => reducer(newState, value, ...args),
prevStateIsUndefined && !valueIsUndefined && initialState
? initialState
: prevState
);
};
};
13 changes: 13 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,19 @@ test('returns initialState', () => {
expect(reducer()).toEqual(initialState);
});

test('passes `initialState` when state is `undefined` and value is defined', () => {
const initialState = { A: 0, B: 0 };
const reducer = reduceReducers(
(state, payload) => ({
...state,
A: state.A + payload
}),
initialState
);

expect(reducer(undefined, 1)).toEqual({ A: 1, B: 0 });
});

test('throws an error if initialState is undefined', () => {
expect(() => {
reduceReducers(undefined);
Expand Down

0 comments on commit 12dc762

Please sign in to comment.