Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accept falsy initalValue #43

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export default (...args) => {
const initialState = typeof args[0] !== 'function' && args.shift();
const initialState = typeof args[0] === 'function' ? null : args.shift();
const reducers = args;

if (typeof initialState === 'undefined') {
Expand All @@ -12,18 +12,23 @@ export default (...args) => {
const prevStateIsUndefined = typeof prevState === 'undefined';
const valueIsUndefined = typeof value === 'undefined';

if (prevStateIsUndefined && valueIsUndefined && initialState) {
if (prevStateIsUndefined && valueIsUndefined && initialState !== null) {
return initialState;
}

return reducers.reduce((newState, reducer, index) => {
if (typeof reducer === 'undefined') {
throw new TypeError(
`An undefined reducer was passed in at index ${index}`
);
}
return reducers.reduce(
(newState, reducer, index) => {
if (typeof reducer === 'undefined') {
throw new TypeError(
`An undefined reducer was passed in at index ${index}`
);
}

return reducer(newState, value, ...args);
}, prevStateIsUndefined && !valueIsUndefined && initialState ? initialState : prevState);
return reducer(newState, value, ...args);
},
prevStateIsUndefined && !valueIsUndefined && initialState !== null
? initialState
: prevState
);
};
};
7 changes: 7 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ test('passes `initialState` when state is `undefined` and value is defined', ()
expect(reducer(undefined, 1)).toEqual({ A: 1, B: 0 });
});

test('passes falsy `initialState` when state is `undefined` and value is defined', () => {
const initialState = '';
const reducer = reduceReducers(initialState, state => state);

expect(reducer(undefined, 1)).toEqual('');
});

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