Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【手写篇 - Day 01】手写函数柯里化 #1

Open
MarsPen opened this issue Mar 24, 2022 · 1 comment
Open

【手写篇 - Day 01】手写函数柯里化 #1

MarsPen opened this issue Mar 24, 2022 · 1 comment

Comments

@MarsPen
Copy link
Owner

MarsPen commented Mar 24, 2022

题目描述

function curry (func) {
  // 此处补全
}

function sum(a, b, c){
  return a + b + c
}

let currySum = curry(sum)
console.log(currySum(1,2,3)) // 6 still callable normally
console.log(currySum(1)(2,3)) // 6 currying of 1st arg
console.log(currySum(1)(2)(3)) // 6 full currying
@MarsPen
Copy link
Owner Author

MarsPen commented Mar 24, 2022

思路

  • 获取参数的形参数个数
  • 返回一个闭包,利用延迟执行函数不断的执行并返回接受余下的参数直到调用结束

代码

// 实现一
function curry(func) {
  return function curried(...args) {
    if (args.length >= func.length) {
      return func.apply(this, args)
    } else {
      return function(...args2) {
        return curried.apply(this, args.concat(args2))
      }
    }
  }
}

function sum(a, b, c){
  return a + b + c
}

let currySum = curry(sum)
console.log(currySum(1,2,3)) // 6 still callable normally
console.log(currySum(1)(2,3)) // 6 currying of 1st arg
console.log(currySum(1)(2)(3)) // 6 full currying
// 实现二
function curry (func) {
  return new Proxy(func, {
    apply(target, thisArg, args) {
      return (args.length >= target.length) ?
        Reflect.apply(...arguments) :
        curry(target).bind(thisArg, ...args);
    }
  })          
}

知识补充

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant