McKilly
McKilly

Reputation: 11

Merging two functions into one

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!

Upvotes: 0

Views: 34

Answers (2)

pnxdxt
pnxdxt

Reputation: 160

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

run(inc, 8)

Upvotes: 2

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

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

Upvotes: 0

Related Questions