Home > OS >  Merging two functions into one
Merging two functions into one

Time:07-29

I have a function that increments numbers (inc), and another that decrements numbers (dec).

I would like to merge them into one as follows:

newFunction(inc, 8) should run inc(8) and newFunction(dec, 3) should run dec(3)

I tried different things but nothing worked so far. Thank you in advance!

CodePudding user response:

const run = (fn, value) => fn(value)

run(inc, 8)

CodePudding user response:

Just pass it as a callback, and use spread for aguments

function newFunction(callback, ...functionArguments) {
  return callback(...functionArguments);
}

newFunction(console.log, "Works with one argument");
newFunction(console.log, "as",  "well", "as",  "with", "multiple");

As you can tell from the code snipper the function console.log got called in both cases

  • Related