-
Notifications
You must be signed in to change notification settings - Fork 108
/
curry.js
54 lines (43 loc) · 1.11 KB
/
curry.js
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
43
44
45
46
47
48
49
50
51
52
53
// curry(fn)(1)(2)(3)
// curry(fn)(1)(2, 3)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length
// 当接受的函数形参数和传入
// 确定参数个数
function curry(fn, ...rest) {
const functionParamsLen = fn.length;
return (...args) => {
args = rest.concat(args);
if (args.length >= functionParamsLen) {
return fn.apply(null, args);
} else {
return curry(fn, ...args);
}
}
}
// 确定参数
const add = curry((a, b, c) => a + b + c);
console.log(add(1, 2, 3))
console.log(add(1, 2)(3))
console.log(add(1)(2)(3))
// 不确定参数个数
function curryInfinity(fn) {
let parmas = [];
const curried = (...args) => {
if(args.length){
parmas = [...parmas,...args]
return curried
}
return fn.apply(null, parmas)
}
curried.toString = () => {
return fn.apply(null, parmas);
}
return curried;
}
function add(...arr){
return arr.reduce((acc,item)=>{
return acc+item
})
}
let curried = curryInfinity(add)
console.log(curried(1)(2)(3)(4)(10,20)())