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

函数式编程之curry函数的实现 #33

Open
qingfengmy opened this issue Jun 25, 2018 · 0 comments
Open

函数式编程之curry函数的实现 #33

qingfengmy opened this issue Jun 25, 2018 · 0 comments

Comments

@qingfengmy
Copy link
Owner

柯里化:多参数变为单参数,英文名为curry

例子

例子:x+y
例子:(a+b)*h/2

const add = function(x, y) {
  return x + y;
};
const area = function(a, b, h) {
  return (a + b) * h / 2;
};
console.log(add(2, 3));// 5
console.log(area(4, 6, 10));// 50

柯里化实现

const curry = function(fn) {
  let args = [];
  const limit = fn.length; // 所需的满额参数数量
  return function justCurry(...params) {
    args = [...args, ...params];

    if (limit == args.length) {
      return fn(...args);
      // return fn.apply(this, args);
      // return fn.call(this, ...args);
    } else {
      return justCurry;
    }
  };
};

console.log(curry(add)(2)(3));// 5
console.log(curry(area)(4)(6)(10));// 50
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