是不是开端清楚起来了? (゚▽゚)
ES6写法的因为应用了 数组解构 及 箭头函数 等语法糖,看上去精简很多,不过思惟都是一样的啦~
- // ES6
- const curry = fn => {
- const _c = (restNum, argsList) => restNum === 0 ?
- fn(...argsList) : x => _c(restNum - 1, [...argsList, x]);
- return _c(fn.length, []);
- }
与其他办法的比较
还有一种大年夜家常用的办法:
把如许的函数传进map:
- function curry(fn) {
- const len = fn.length;
- return function judge(...args1) {
- return args1.length >= len ?
- fn(...args1):
- function(...args2) {
- return judge(...[...args1, ...args2]);
- }
- }
- }
- // 应用箭头函数
- const curry = fn => {
- const len = fn.length;
- const judge = (...args1) => args1.length >= len ?
- fn(...args1) : (...args2) => judge(...[...args1, ...args2]);
- return judge;
- }
与本篇文┞仿先前提到的办法比较的话,发明这种办法有两个问题:
-
依附ES6的解构(函数参数中的 ...args1 与 ...args2);
-
机能稍差一点。
机能问题
- console.time("curry");
- const plus = curry((a, b, c, d, e) => a + b + c + d + e);
- plus(1)(2)(3)(4)(5);
- console.timeEnd("curry");
在我的电脑(Manjaro Linux,Intel Xeon E5 2665,32GB DDR3 四通道1333Mhz,Node.js 9.2.0)上:
-
其他办法低砟瓯约 0.345ms
差的┞封一点猜测是闭包的原因。因为闭包的拜访比较耗机能,而这种方法形成了两个闭包:fn 和 len,前面提到的办法只形成了
推荐阅读
开辟者大年夜赛路演 | 12月16日,技巧立异,北京不见不散至少大年夜今朝的体验上来看,大年夜家更迎接屏下指纹而不是人脸辨认,毕竟新技巧过度须要一步步来.... 指纹辨认真的要彻底被手机摈>>>详细阅读
本文标题:JS中的柯里化及精巧的自动柯里化实现
地址:http://www.17bianji.com/lsqh/39665.html
1/2 1