huabingtao / front-knowledge

基于Issues系统学习前端技术
0 stars 0 forks source link

实现函数柯理化 #78

Open huabingtao opened 4 years ago

huabingtao commented 4 years ago

实现函数柯理化

// 木易杨
function currying(fn, length) {
  length = length || fn.length;     // 注释 1
  return function (...args) {           // 注释 2
    return args.length >= length    // 注释 3
        ? fn.apply(this, args)          // 注释 4
      : currying(fn.bind(this, ...args), length - args.length) // 注释 5
  }
}

// Test
const fn = currying(function(a, b, c) {
    console.log([a, b, c]);
});

fn("a", "b", "c") // ["a", "b", "c"]
fn("a", "b")("c") // ["a", "b", "c"]
fn("a")("b")("c") // ["a", "b", "c"]
fn("a")("b", "c") // ["a", "b", "c"]