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

柯里化函数 #15

Open
xiaohesong opened this issue Dec 11, 2018 · 0 comments
Open

柯里化函数 #15

xiaohesong opened this issue Dec 11, 2018 · 0 comments
Labels
example 一些例子 higher-order function 记录一些有意思的高阶组件

Comments

@xiaohesong
Copy link
Owner

之前有写过一篇文章,是说柯里化函数和函数组合, 看完之后真是大受脾益,尤其是在看redux源码的时候,就感觉很顺通。

今天上午看了下简书,发现了一个被面试到的问题,思考了下。问题是这样的:

函数闭包与柯里化(让手写一个函数完成求和操作,func(1)(2)(3)、func(1,2)(3)和func(1,2,3)都能保证可以正常求和)

function add(...args) {
  return args.reduce((total, item) => total = total + item, 0)
}

function func(fn){
  return (length) => (...args) => (length - args.length) ? func(fn)(length).bind(null, ...args) : fn(...args)
}
add3 = func(add)(3)
add3(1)(2)(3)
add3(1,2)(3)
add3(1,2,3)

上面的func看起来有些怪怪的, 有这个func(fn)(length),那么我们来改下下

function func(fn){
  return (length) => varFun =  (...args) => (length - args.length) ? varFun.bind(null, ...args) : fn(...args)
}
@xiaohesong xiaohesong added higher-order function 记录一些有意思的高阶组件 example 一些例子 labels Dec 11, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
example 一些例子 higher-order function 记录一些有意思的高阶组件
Projects
None yet
Development

No branches or pull requests

1 participant