闭包应用-偏应用与柯里化

95 阅读1分钟

偏应用函数 Partial application

In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity.

const partial = (fn, ...args) => (...moreArgs) => fn(...args, ...moreArgs)
const add = (x, y, z) => x + y + z
const fivePlus = partial(add, 2, 3)
fivePlus(4)

柯里化 Curried functions

柯里化是将一个多参数函数转换成多个单参数函数,也就是将一个n元函数转换成n哥一元函数

const multiply=(x,y,z)=>x+y+z
function current(fn){
  return function currented(...args){
    if(args.length>=fn.length){
      return fn.apply(this,args)
    }else{
      return function(){
        return currented.apply(null,[...args,...arguments])
      }
    }
  }
}
const add=current(multiply)
add(1)(2)(3)

实例:分割函数转CSV

const split = (regex, str) => ("" + str).split(regex);
const elements = split("v1,v2,v3", /,\s*/);
const partial =
  (f, ...args) =>
  (...moreArgs) =>
    f(...args, ...moreArgs);
const csv = partial(split, /,\s*/);
const s = csv("v1,v2,v3");
console.log(s);