0

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

2
  • It sounds like you want if (a === 13) return 4; but I can't figure how you want to fit an array into this, and even less that array of functions you have. Mind rephrasing a bit? Commented Aug 5, 2020 at 0:12
  • I don't know why they closed this, it's clear what you want to do: array.reduce((ret, fn) => fn(ret), 13) will output 4 Commented Aug 5, 2020 at 22:04

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.