0

The compose function in Redux is really simple for the most part and I understand how to use it.

export default function compose(...funcs) {
  if (funcs.length === 0) {
    return arg => arg
  }

  if (funcs.length === 1) {
    return funcs[0]
  }

  return funcs.reduce((a, b) => (...args) => a(b(...args)))
}

However, this one part of the last bit seems really obscure to me:

funcs.reduce((a, b) => (...args) => a(b(...args)))

What is the ...args part? I understand these are rest parameters but what is it evaluating to? Where is it coming from?

Chris Snow
  • 23,813
  • 35
  • 144
  • 309
Amit Erandole
  • 11,995
  • 23
  • 65
  • 103
  • 2
    [`...` is not an operator](http://stackoverflow.com/a/37152508/218196). You can read about [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters) and ["call spread"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator) on MDN. *"what is it evaluating to"* They are both syntactic constructs with different meanings. The first one means that all arguments are collected in an array accessible via `args`. The second one means to pass all entries of (the iterable referenced by) `args` as arguments to `b`. – Felix Kling Apr 16 '17 at 01:10
  • awesome - good catch - will read this – Amit Erandole Apr 16 '17 at 01:11
  • Possible duplicate of [Understanding compose functions in redux](https://stackoverflow.com/questions/41357897/understanding-compose-functions-in-redux) – therewillbecode Aug 07 '18 at 12:26

1 Answers1

1

Compose is just allowing you to write

compose(func1, func2, func3, func4)

instead of

func1(func2(func3(func4))))

In case of

funcs.reduce((a, b) => (...args) => a(b(...args))) 

.reduce is a function of array, you can read about Array Reduce function

It is returning

(...args) => a(b(...args);

and giving you an option to pass some parameters to the nested functions.

for example: It is allowing you to write something like this:

 nestedFunc = compose(func1, func2, func3);

 nestedFunc({key: value})

which will result in

func1(func2(func3({key: value})))

Read more about compose function

Community
  • 1
  • 1
Niraj
  • 477
  • 6
  • 16