Repository navigation
Expand file tree
/
Copy pathfunction-currying.js
More file actions
86 lines (77 loc) · 2.13 KB
/
Copy pathfunction-currying.js
File metadata and controls
86 lines (77 loc) · 2.13 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
console.log("Hello World!");
function add(a, b, c, d, e) {
console.log(arguments);
if (arguments.length == 0) return 0;
return [...arguments].reduce((prev, cur) => prev + cur);
}
// console.log(add(1, 2, 3, 4, 5));
function curryCustom(fn) {
// args.length can be 1,2,3
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
} else {
return (...moreArgs) => curried(...args, ...moreArgs);
}
};
}
// function curryCustom(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));
// };
// }
// };
// }
// let newSum = curryCustom(add);
// console.log(newSum);
// let test = newSum(1)(2, 4)(3)(5);
// console.log(test);
// function curry(fn) {
// return function inner(...args){
// if([...args].length > 0){
// return inner(...args)
// }else{
// return fn.apply()
// }
// }
// }
function infiniteCurry(fn) {
// curried function here to return a function because it needs to remember the args
// and separate it from the params it got from curry function
const curried = (...args) => {
return (...params) => {
console.log(params)
if (params.length === 0) {
console.log("empty array is true", params)
return args.reduce((acc, a) => {
return fn.call(fn, acc, a)
}, 0);
} else {
return curried(...args, ...params);
}
}
};
// you need to executed curried function which will return a params function
return curried();
}
// const infiniteCurry = fn => {
// const next = (...args) => {
// console.log("arguments avl",args);
// return z => {
// console.log("x value",z);
// if (!z) {
// return args.reduce((acc, a) => {
// return fn.call(fn, acc, a)
// }, 0);
// }
// return next(...args, z);
// };
// };
// return next();
// };
const iSum = infiniteCurry((x, y) => x + y);
console.log(iSum(1)(3)(4,8)(2)());