happypoulp / redux-tutorial

Learn how to use redux step by step
3.76k stars 546 forks source link

10_middleware.js: Consider Curried Middle-ware #70

Closed meChrisReed closed 8 years ago

meChrisReed commented 8 years ago

In the file 10_middleware.js there is an example of a function that returns functions, but only the last one executes anything. When I saw it immediately recognized it as an opportunity to apply more functional patterns. Specifically it looks like a primitive curry.

I have not yet finished the tutorial or used Redux. So if there a reason later revealed or not covered in the tutorial please let me know.

The original code:

var thunkMiddleware = function ({ dispatch, getState }) {
    // console.log('Enter thunkMiddleware');
    return function(next) {
        // console.log('Function "next" provided:', next);
        return function (action) {
            // console.log('Handling action:', action);
            return typeof action === 'function' ?
                action(dispatch, getState) :
                next(action)
        }
    }
}

Suggested code with curry:

const curry = (fn, ...args) => (
  args.length === fn.length ? 
    fn(...args) : 
    curry.bind(null, fn, ...args)
);

var thunkMiddleware = curry(({dispatch, getState}, next, action) => (
   typeof action === 'function' ?
     action(dispatch, getState) :
     next(action))
);

I tested it and it worked just fine in the context of the tutorial.

happypoulp commented 8 years ago

Thanks for the suggestion! I'll add a side-note about that approach in 10_middleware.js. Keeping this issue open until it's done.

meChrisReed commented 8 years ago

Cool, thank you.

happypoulp commented 8 years ago

Done in https://github.com/happypoulp/redux-tutorial/commit/542389fb0fa57411165418a90190d5f18f3b4946 .