JavaScript中的管道功能 [英] piping functions in JavaScript

查看:160
本文介绍了JavaScript中的管道功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能有一个JavaScript函数让我们说 piper()它将几个函数作为参数,并返回一个新函数,将其参数传递给第一个函数,然后将结果传递给第二个,然后
将第二个结果传递给第三个,依此类推,最后返回最后一个函数的输出。



类似 piper(foo,fee,faa)(10,20,30)等同于调用 faa(费用(foo(10,20,30)))



ps:
It我是几天前做的一次采访的一部分。

解决方案

对于arbritrary数量的函数,您可以使用此ES6函数:



< pre class =snippet-code-js lang-js prettyprint-override> function piper(... fs){return(... args)=> fs.reduce((args,f)=> [f.apply(this,args)],args)[0];} //示例调用:var result = piper(Math.min,Math.abs,Math。 sqrt)(16,-9,0)//输出结果:console.log(result);



ES5语法相同:



  function piper(/ * functions * /){var fs = [] .slice.apply(arguments); return函数(/ * arguments * /){return fs.reduce(function(args,f){return [f.apply(this,args)];} .bind(this),[] .slice.apply(arguments) )[0]; } .bind(this);} //示例调用:var result = piper(Math.min,Math.abs,Math.sqrt)(16,-9,0)//输出结果:console.log(result);  


How can I have a JavaScript function let's say piper() which takes several functions as its arguments and it returns a new function that will pass its argument to the first function, then pass the result to the second, then pass the result of the second to the third, and so on, finally returning the output of the last function.

Something like piper(foo, fee, faa)(10, 20, 30) would be equivalent to calling faa(fee(foo(10,20,30))).

ps: It was a part of an interview, that I did few days ago.

解决方案

For an arbritrary number of functions you could use this ES6 function:

function piper(...fs) {
    return (...args) => fs.reduce((args,f) => [f.apply(this,args)],args)[0];
}
// Example call:
var result = piper(Math.min, Math.abs, Math.sqrt)(16, -9, 0)
// Output result:
console.log(result);

The same in ES5 syntax:

function piper(/* functions */) {
    var fs = [].slice.apply(arguments);
    return function (/* arguments */) { 
        return fs.reduce(function (args,f) {
            return [f.apply(this,args)];
        }.bind(this), [].slice.apply(arguments))[0];
    }.bind(this);
}
// Example call:
var result = piper(Math.min, Math.abs, Math.sqrt)(16, -9, 0)
// Output result:
console.log(result);

这篇关于JavaScript中的管道功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆