Simple Composition with Array.Reduce
Here it is:
First, the spread operator here has the effect of accepting all the arguments as a single array, allowing us to use array methods on function's parameters.
So later, we won't have to pass an array of functions, and can just pass an arbitrary number of parameters:
Since the compose function must itself return a function, we need to pass a callback function to the reduce method that returns a function:
Previous will start as funcs and current as funcs, but previous will accumulate each function in the array with each call of the callback function:
Once it's reached the end of the array, you have a function that contains calls to each function in the original array, with the very first function call containing your initial x. By returning functions that accept an x with each callback, you ensure that the x can be passed all the way back to the first function call.
For composition to work, the functions must all be unary (i.e. the must all take just one parameter). This is why curried functions are so useful - they make it much easier to compose functions together.
With compose, you can then create functions by simply stringing other functions together:
And also: if you prefer to have functions evaluated from right to left, you can use reduceRight instead: