Home > Software engineering >  How to .reduce() an array that contains functions?
How to .reduce() an array that contains functions?

Time:12-16

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?

CodePudding user response:

Yes, like so:

function fun1(a){ return a.toUpperCase() }
function fun2(b){ return b.substring(0, 10) }
function fun3(c){ return c.length }
const funcArray = [fun1, fun2, fun3]
const someString = "Trying to create compose from redux using reduce"

const result = funcArray.reduce((a, c) => c(a), someString)
console.log(result)

CodePudding user response:

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))

CodePudding user response:

this example here, does the subtraction of the number elements in an array

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>Subtract the numbers in the array, starting from the left:</p>

<p id="demo"></p>

<script>
const numbers = [175, 50, 25];
document.getElementById("demo").innerHTML = numbers.reduce(myFunc);

function myFunc(total, num) {
  return total - num;
}
</script>

</body>
</html>
  • Related