Skip to content
Advertisement

How to .reduce() an array that contains functions?

Lets say we have an array of functions

function fun1(){}
function fun2(){}
function fun3(){}
const funcArray = [fun1, fun2, fun3]
const someString = "Trying to create compose from redux using reduce"

Is there a way to funcArray.reduce() and have all three functions apply on the string using reduce?

Advertisement

Answer

Compose is an HOC, which means it takes function and returns function. Trick is to decide when to execute the functions.

Here is a sample function that will work like redux’s compose

function fun1(a){ return a * 2 }
function fun2(a){ return a * 3 }
function fun3(a){return a * 4}
const funcArray = [fun1, fun2, fun3]
const someString = "Trying to create compose from redux using reduce"

const state = 5
const compose = (...handlers) => {
  return (func) => {
    const newState = handlers.reduce(
      (_state, handler) => handler(_state),
      state
    )
    func(newState)
  }
}

compose(...funcArray)((value) => console.log(value))
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement