Pop
Pop

Reputation: 31

Array of functions in JS

How do I make a function that takes an input, for example 13, and then executes all the functions in the array on that input and returns the output, which would be 4 in this case

array = [
  function(a){ return a * 2 },
  function(a){ return a + 1000},
  function(a){ return a % 7 }
]

function f(array){
  console.log(array);
}

Upvotes: 0

Views: 727

Answers (2)

Maxime Helen
Maxime Helen

Reputation: 1412

As Dave replied in the question, you could use reduce to make this happen:

const runFunctionSequence = (sequence, input) => sequence.reduce((accumulatedOutput, fun) => fun(accumulatedOutput), input);

const arr = [
  function(a){ return a * 2 },
  function(a){ return a + 1000},
  function(a){ return a % 7 }
];

console.log(runFunctionSequence(arr, 13)); // -> 4

Upvotes: 1

Charlie
Charlie

Reputation: 23798

You want to run a number and each result through series of functions which are stored in an array.

arr = [
  function(a){ return a * 2 },
  function(a){ return a + 1000},
  function(a){ return a % 7 }
]

function runAll(input){
  
  let output = input;
  for (let f of arr) {
    output = f(output)
  }
  
  return output;
}


console.log(runAll(13)) //4

Upvotes: 0

Related Questions