2

I'm looking to lower my overhead on code like this

foo(bar(baz("hello"))) // function hell

ideally something like this

var fbb = bind(foo, bar, baz)
foo("hello")

Does this exist? Native or library?

I looked through underscore and bind.

ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

3 Answers3

1
function getCaller(first) {
    var rest = Array.prototype.slice.call(arguments, 1);
    return function (value) {
        return rest.reduce(function (previous, next) {
            return next(previous);
        }, first(value));
    };
}

function foo(string) {
    return string + ' world!';
}

function bar(string) {
    return string + ' Hi';
}

function baz(string) {
    return string + ' Mom!';
}

var caller = getCaller(foo, bar, baz);
console.log(caller('Hello'));
// Prints: Hello world! Hi Mom!
Jackson
  • 9,188
  • 6
  • 52
  • 77
  • Hey! Thanks so much for this! I was wondering if there's any way to accept multiple arguments for the last function? I know I used strings in the example above but my real-life example looks something more like `await(Promise.promisify(fs.copy(newIconPath, appIconPath)))` thoughts? – ThomasReggi Dec 02 '14 at 09:40
  • Functions only return one value so that makes your requirement illogical. However, you could make a special case where, if an array is returned, `apply` the array instead of passing the array as an argument to `next`, but that prevents you from passing an array as an argument to `next`, which is a very likely scenario. – Jackson Dec 02 '14 at 09:45
1

Underscore has the compose function which will do what you want:

var composite = _.compose(foo, bar, baz);

composite('hello');

function foo(a1){
  return 'foo' + a1;
}  

function bar(a2){
  return 'bar' + a2;
}

function baz(a3){
  return 'baz' + a3;
}

alert(foo(bar(baz("hello"))));

var composite = _.compose(foo, bar, baz);

alert( composite('hello') );
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
Gruff Bunny
  • 27,738
  • 10
  • 72
  • 59
0
var bind = function() {
  var fns = Array.prototype.slice.call(arguments).reverse();
  return function(value) {
    for (var key in fns) {
      var fn = fns[key];
      console.log(fn);
      value = fn(value);
    }
    return value;
  }
}

function plusTomato(value) {
  return value + "tomato";
}

function plusPear(value) {
  return value + "pear";
}

var plus = bind(plusTomato, plusPear);

var y = plus("pancake"); //pankaketomatopear
console.log(y);
var x = plusTomato(plusPear("pancake")); //pankaketomatopear
console.log(x);
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • Why do you call that function `bind`? It doesn't bind anything. Also, [never enumerate arrays using `for in`](http://stackoverflow.com/q/500504/1048572) – Bergi Dec 02 '14 at 11:25