2rever的前端小站

js柯里化curry函数实现

Word count: 143 / Reading time: 1 min
2018/10/23 Share

curry函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function curry(f, l = f.length) {
return function(...args1) {
if (args1.length >= l) {
return f(...args1)
} else {
return function(...args2) {
if (args1.length + args2.length >= l) {
return f(...args1, ...args2)
} else {
return function(...args3) {
if (args1.length + args2.length + args3.length >= l) {
return f(...args1, ...args2, ...args3)
else {
return function(...args4) {

}
}
}
}
}
}
}
}

function curry(f, l = f.length) {
return function(...args) {
if (args.length >= l) {
return f(...args)
} else {
return curry(f.bind(null, ...args), l - args.length)
}
}
}

function f(a,b,c,d) {
return a + b + c + d
}

ff = curry(f)(1) ()()()()()

ff(4) //10
ff(5) //11
CATALOG
  1. 1. curry函数