Create a simpler way of nesting functions

百般思念 提交于 2020-01-04 17:37:29

问题


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.


回答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>



回答2:


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!



回答3:


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


来源:https://stackoverflow.com/questions/27245652/create-a-simpler-way-of-nesting-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!