-
Notifications
You must be signed in to change notification settings - Fork 0
/
currying.js
66 lines (49 loc) · 1.42 KB
/
currying.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
54
55
56
57
58
59
60
61
62
63
64
65
66
//currying
//it is a technique in functional programming in which a function with multiple arguments is transformed into serveral function with single argument in sequence
//it can be done in 2 ways
//1: bind
const add = (x, y) => {
return x + y;
}
const addTwo = add.bind(this, 2);
const res = addTwo(10);
// console.log("function currying using bind", ans);
//2: closure
function addClosure(x) {
return function(y) {
return x + y
}
}
const addClosureThree = addClosure(3);
const ansClosure = addClosureThree(5);
// console.log("function currying using closure", ansClosure);
// sum(1)(2)(3)....()
// 1+2+3+4...
function sum(x) {
return function(y) {
return y ? sum(x + y) : x
}
}
const sumVal = sum(1)(2)(3)(4)(5)(6)();
// console.log("sumVal", sumVal);
// curryAltSum(1)(2)(3, 4)(5, 6, 7)(8)(9, 10)...()
// 1+2-3+4-5+6-7+8-9+10
let isSum = true;
function curryAltSum(...args1) {
let sum = args1[0];
return function(...args2) {
for (let i = 1; i < args1.length; i++) {
if (isSum) sum += args1[i]
else sum -= args1[i]
isSum = !isSum;
}
for (let i = 0; i < args2.length; i++) {
if (isSum) sum += args2[i]
else sum -= args2[i]
isSum = !isSum;
}
return args2.length ? curryAltSum(sum) : sum
}
}
const ans = curryAltSum(1)(2)(3, 4)(5, 6, 7)(8)(9, 10)()
console.log("ans", ans)