Selenir Selenir - 5 months ago 12
Javascript Question

Reduce array of callback functions to one callback

I'm wondering how can I create a function which calls all functions from array without explicitly creating one. Im talking about plain javascript (or maybe some underscore.js/lodash helpers, but I haven't found anything useful).

Let's say we have a method which takes a callback:

function doSmth(cb) {
console.log('doing smth');
cb();
}


Now we have three functions which we'd like to call, but we don't like to explicitly create a wrapper function.

function write1() {
console.log(1)
}

function write2() {
console.log(2)
}

function write3() {
console.log(3)
}


Can we somehow reduce an array of
[write1, write2, write3]
to single function? I've tried binding
Function.prototype.call
to
Array.prototype.forEach
but I didn't get anywhere.

Edit: I forgot to mention that we don't want to modify
doSmth

Answer

You can use forEach with a little helper function.

let invoke = (fn, ...args) => fn(...args);
arr.forEach(invoke);

// or for an array of the results
let results = arr.map(invoke);

// es5 translation of invoke
var invoke = function() {
  var fn = arguments[0];
  var args = [].slice.call(arguments, 1, arguments.length);
  return fn.apply(null, args);
};

let doIt = arr.forEach.bind(arr, invoke)
takesACallback(doIt);