-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path手写Currying.html
More file actions
119 lines (104 loc) · 3.38 KB
/
手写Currying.html
File metadata and controls
119 lines (104 loc) · 3.38 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TEST</title>
<style>
body {
padding: 16px 32px;
}
pre {
padding: 16px;
line-height: 1.5;
background-color: #f5f5f5;
}
</style>
</head>
<body>
<H3>7. 实现一个JS函数柯里化</H3>
<script>
// 方法一
// function currying(func) {
// var args = Array.prototype.slice.call(arguments, 1);
// return function currying() {
// Array.prototype.push.apply(args, arguments);
// if (args.length >= func.length) {
// return func.apply(null, args);
// }
// return currying
// };
// }
// 方法二
// function currying(func) {
// var args = Array.prototype.slice.call(arguments, 1);
// return function currying() {
// Array.prototype.push.apply(args, arguments);
// if (arguments.length === 0) {
// return func.apply(null, args);
// }
// return currying;
// };
// }
// 方法三
function currying(func) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
var newArgs = args.concat([].slice.call(arguments));
if (newArgs.length === func.length) {
return func.apply(this, newArgs);
}
newArgs.unshift(func);
return currying.apply(this, newArgs);
};
}
console.log("============== currying ==================");
function multiFn(a, b, c) {
return a * b * c;
}
var multi = currying(multiFn);
console.log(
multi(2, 22,4,44,4),
multi(2)(3)(4),
multi(2, 3, 4),
multi(2)(3, 4),
multi(2, 3)(4)
);
// 实现无限极累加 add(1)(2)(3)(4)...
(function () {
function addTo() {
var sum = 0
for (var i = 0, l = arguments.length; i < l; i++) {
sum += arguments[i];
}
return sum;
}
function currying(func) {
var args = []
const _currying = function () {
Array.prototype.push.apply(args, arguments)
// console.log(args)
if (arguments.length === 0) {
return func.apply(null, args)
}
return _currying;
}
// 字符类型
_currying.toString = function () {
return func.apply(null, args);
};
// 数值类型
_currying.valueOf = function () {
return func.apply(null, args);
};
return _currying
}
var add = currying(addTo)
console.log(add(1)(3)) // ƒ 4
console.log(add(1)(3)()) // 4
console.log(add(1)(3).valueOf()) // 4
}())
</script>
</body>
</html>