Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Does reduceReducers() Work?

Code comes from the reduce-reducer repo:

   export function reduceReducers(...reducers) {
        return (previous, current) =>
            reducers.reduce(
                (p, r) => r(p, current),
                previous
            );
    }

I understand that the purpose of this function is to flatten the different slices of state in Redux, see here, but I don't understand how this function works. I have looked up MDN, but still don't understand.

What is calling previous, current and what do p and r represent. I can't identify the variables being called.

Edit

Mark Erikson defines this function in his Practical Redux Series:

reduceReducers is a nifty little utility. It lets us supply multiple reducer functions as arguments and effectively forms a pipeline out of those functions, then returns a new reducer function. If we call that new reducer with the top-level state, it will call the first input reducer with the state, pass the output of that to the second input reducer, and so on.

Edit 2

I wrote a post to explain reduceReducers().

like image 555
Avi Kaminetzky Avatar asked Jan 04 '18 22:01

Avi Kaminetzky


1 Answers

Perhaps it's a bit clearer if written this way:

export function reduceReducers(...reducers) {
    return function (state, action) {
        const reducerFunction = function (accumulator, currentValue) {
            return currentValue(accumulator, action);
        }

        return reducers.reduce(reducerFunction, state);
    }
}

Parameters & variables:

  • reducers: the array of reducers you want to reduce. In the question you linked this would be [reducerAdd, reducerMult]
  • state: (formerly previous) the redux state object
  • action: (formerly current) the action object
  • accumulator: (formerly p) the object used by the reduce() function. Initial value is the previous redux state
  • currentValue: (formerly r) the current reducer function to be run by the reduce() function

reduceReducers() returns a function (in your linked answer it's the addAndMult() function) that gets called by redux when it's processing dispatched actions. redux passes in it's previous state with the current action.

reduce() is run on the array of reducers ([reducerAdd, reducerMult]) which uses the reducerFunction (previously an anonymous arrow function, but I've named it for clarity) to call each reducer in turn on the redux state object that is passed in.

Hopefully that makes sense.

like image 172
bmceldowney Avatar answered Sep 17 '22 21:09

bmceldowney