作家
登录

JS中的柯里化及精巧的自动柯里化实现

作者: 来源: 2017-12-11 16:20:34 阅读 我要评论

null, argsList) : 
  •       function(x) { 
  •         return _c(restNum - 1, argsList.concat(x)); 
  •       }; 
  •   } 
  •   return _c(fn.length, []); // 递归开端 
  • 是不是开端清楚起来了? (゚▽゚)

    ES6写法的因为应用了 数组解构箭头函数 等语法糖,看上去精简很多,不过思惟都是一样的啦~

    1. // ES6 
    2. const curry = fn => { 
    3.   const _c = (restNum, argsList) => restNum === 0 ? 
    4.     fn(...argsList) : x => _c(restNum - 1, [...argsList, x]); 
    5.  
    6.   return _c(fn.length, []); 

    与其他办法的比较

    还有一种大年夜家常用的办法:

    把如许的函数传进map:

    1. function curry(fn) { 
    2.   const len = fn.length; 
    3.   return function judge(...args1) { 
    4.     return args1.length >= len ? 
    5.     fn(...args1): 
    6.     function(...args2) { 
    7.       return judge(...[...args1, ...args2]); 
    8.     } 
    9.   } 
    10.  
    11. // 应用箭头函数 
    12. const curry = fn => { 
    13.   const len = fn.length; 
    14.   const judge = (...args1) => args1.length >= len ? 
    15.     fn(...args1) : (...args2) => judge(...[...args1, ...args2]); 
    16.   return judge; 

    与本篇文┞仿先前提到的办法比较的话,发明这种办法有两个问题:

    1. 依附ES6的解构(函数参数中的 ...args1...args2);

    2. 机能稍差一点。

    机能问题

    1. console.time("curry");
    2. const plus = curry((a, b, c, d, e) => a + b + c + d + e); 
    3. plus(1)(2)(3)(4)(5); 
    4. console.timeEnd("curry"); 

    JS中的柯里化及精细的主动柯里化实现

    在我的电脑(Manjaro Linux,Intel Xeon E5 2665,32GB DDR3 四通道1333Mhz,Node.js 9.2.0)上:

    • 其他办法低砟瓯约 0.345ms

    差的┞封一点猜测闭包的原因。因为闭包的拜访比较耗机能,而这种方法形成了两个闭包fnlen,前面提到的办法只形成了


      推荐阅读

      人脸识别难用!苹果拿下屏下指纹 新iPhone爽了

    开辟者大年夜赛路演 | 12月16日,技巧立异,北京不见不散至少大年夜今朝的体验上来看,大年夜家更迎接屏下指纹而不是人脸辨认,毕竟新技巧过度须要一步步来.... 指纹辨认真的要彻底被手机摈>>>详细阅读


    本文标题:JS中的柯里化及精巧的自动柯里化实现

    地址:http://www.17bianji.com/lsqh/39665.html

    关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)