Javascript es6 double arrow functions

I'm trying to wrap my head around some of the arrow functions that are so common in reactions, and these are tools.

In the following example:

export default function applyMiddleware(...middlewares) { return (createStore) => (reducer, preloadedState, enhancer) => { // snip actual enhancer logic return { ...store, dispatch } } } 

Description above in words:

  • Our exported function (applyMiddleware) accepts an array parameter with an extension.
  • Then applyMiddleware returns an unnamed function with the createStore parameter, which this time returns another unnamed function with three parameters.

So, without arrows, it will look like this:

 export default function applyMiddleware(...middlewares) { return function(createStore){ return function(reducer,preloadedState,enhancer){ //some logic return{...store,dispatch} } } } 

My questions:

  • Am I right?
  • What is the shared / code paradigm we see here?
+5
source share
1 answer

The answer to your first question is more or less (see my comment). The answer to your second question is that the pattern you see is a combination of closure and currying . The initial parameters of the exported function are collected in an array called "middlewares", which returns the returned functions (i.e., has access). Then the function can be called again with another parameter "createStore", after which another function is returned, which can take even more parameters. This allows partial application of the parameters. For a more trivial (and perhaps more easily understood) example, let's take the add function, which adds two numbers:

 let add = (x, y) => x + y; 

Not very interesting. But let's break it down so that it can take the first number and return a function that takes the second:

 let add = x => y => x + y; let add3 = add(3); let seven = add3(4); // 7 

This may not seem like a big win for our add function, but you started with a much more intelligent real world. In addition, instead of manually drawing, it is possible (and desirable) to use the curry function that does this for you, many popular libraries (lodash, underscore, ramda) implement curry for you. An example of using Ramda:

 let add = R.curry((x, y) => x + y); let add3 = add(3); let five = add3(2); let also5 = add(3, 2); let still5 = add(3)(2); // all are equivalent. 
+12
source

All Articles