函数柯里化

161 阅读1分钟

柯里化作用

参数复用

当一个参数比较固定,都是同一个值,可以用函数柯里化进行参数复用

  • 未复用

      function uri(protocol,hostname,pathnmae){
          return protocol + hostname,pathnmae
      }
      ​
      uri('http://','127.0.0.1','index1.html')
      uri('http://','192.168.3.56','index2.html')
      uri('http://','127.0.0.1','index2.html')
    
  • 复用

      function uri_curring(protocol){
          return function(hostname,pathnmae){
              return protocol + hostname,pathnmae
          }
      }
      ​
      let uri_http = uri_curring('http')
      uri_http('127.0.0.1','index1.html')
      uri_http('192.168.3.56','index2.html')
      uri_http('127.0.0.1','index2.html')
    

兼容性检测

  • 一个函数就可以实现不太兼容性的功能
  const whichEvent = (function(){
      if(window.addEventListener){
          return function(element,type,listener,useCapture){
              element.addEventListener(type,function(e){
              listener.call(element,e)
           },useCapture)
      }
      }else if(window.attachEvent){
          return function(element,type,handle){
              element.attachEvent('on'+type,function(e){
               handle.call(element,e)
           })}
      }
  })()

延迟执行

  add(1,2,3) = 6
  add(1,2,3)(4) = 10
  add(1)(2)(3)(4)(5) = 15

实现add函数

  function add(){
      //第一个括号的参数
      let args = [...arguments];
      let inner = function(){
          args.push(...arguments)
          return inner
      }
  ​
      //重写toString()
      inner.toString = function(){
          return args.reduce((pre,cur)=>pre+cur)
      }
  ​
      return inner
  }
  ​
  const result = add(1)(2)(3)(3)
  console.log(result);
  • add(1)(2)(3)(4)(5)() = 15 必须加上一个没有带参数的括号代表结束

    不定长

      
              function curring(fn){
                  let args = []
                  return function inner(...newArgs){
                      if(newArgs.length){
                          args = [...args,...newArgs]
                          return inner
                      }else{
                          //以后一个括号,没传参
                          return fn.apply(this,args)
                      }
                  }
              }
      ​
              let curry_add = curring(add)
              console.log(curry_add(1)(2)(3)());
    

    定长

              function add(a,b,c){
                  return a+b+c
              }
      ​
              function curring_count(fn){
                  let args = [],
                      len = fn.length
                  return function inner(...newArgs){
                      args = [...args,...newArgs]
                      if(args.length < len){
                          return inner
                      }else{
                          return fn.apply(this,args.slice(0,len))
                      }
                  }
              }
      ​
              let curry_add = curring_count(add,5)
              console.log(curry_add(1,2)(3)(4));
      ​