问题描述
这是代码:
const Pipe = (...fns) => fns.reduce((f,g) => (...args) => g(f(...args)));
所以(... fns)fns参数变成一个数组?在这部分:
So by (...fns) the fns arguments becomes an array right? in this part:
(f,g) => (...args)
args来自哪里?是否有默认的args参数?我无法阅读这部分内容:
where did args came from? is there a default args parameter? and I cannot read this part:
(...args) => g(f(...args))
我不能用我的头包住这个嵌套这里减少是如此令人困惑。
I just cannot wrap my head with this nesting and what reduce does here is so confusing.
推荐答案
为了更好的理解,我已经将代码翻译成块级,如下所示尝试解释有关新手开发者的代码帮助。为了更好地实施 @naomik 有解决方案。
For better understanding i have translated the code to block level as below trying to explain the code in question for a novice developer which helps. For better implementation @naomik has solution.
ES6
const Pipe = (...fns) => {
return fns.reduce((f, g) => {
return (...args) => {
return g(f(...args))
}
})
};
等效的ES5实现:
var Pipe = function () {
var fns = [];
for (var _i = 0; _i < arguments.length; _i++) {
fns[_i] = arguments[_i];
}
return fns.reduce(function (f, g) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return g(f.apply(void 0/*Undefined or can use 'null'*/, args));
};
});
};
逐个细节:(阅读代码注释以获得更好的理解)
const inc = (num) => num+1 //Function to increment the number
const dbl = (num) => num*2 //Function double's the number
const sqr = (num) => num*num //Function Square's the number
/*Function breakdown*/
const _pipe = (f, g) => (...args) => g(f(...args)); //Second part
const Pipe = (...fns) => fns.reduce(_pipe); //First part
const incDblSqr = Pipe(inc, dbl, sqr) //Piping all the functions
const result = incDblSqr(2) // Piped function
console.log(result) // ((2+1)*2) ^ 2 = 36
解释:
有关的代码有助于将结果从一个函数传递给另一个函数。
The code in question helps to pipe the result from one function to another function.
以上代码的逐步过程:
- 第一个数字增加1
- 递增后的结果累积并管道传输到另一个
函数,其中数字乘以2(加倍) - 最后,双倍数字是平方的下一个功能
所有这些都是使用可以访问缩减参数的闭包来实现的)
All these are achieved using closures which has access to the reducing arguments (Read the article linked below for clarity).
结论:
所涉及的代码有助于管理n个操作的函数结果
Conclusion:The code in question helps to pipe the n-number of functions that operates on the result emitted by previous function.
Andrew L. Van Slaars的最佳文章:
请阅读上述文章以了解清晰度以及@naomik解决方案
Please read the above article for clarity and also @naomik solution
这篇关于我需要帮助理解其余的和传播操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!