forked from dreamapplehappy/hacking-with-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcurry.js
55 lines (46 loc) · 1.42 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
// basic
function describe(fruit) {
return function (name) {
var msg = name + ' like eat ' + fruit + '.';
console.log(msg);
return msg;
}
}
var appleLiker = describe('apple');
appleLiker('Dreamapple');
appleLiker('Tom');
// advanced
function curryHelper(fn) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
var newArgs = Array.prototype.slice.call(arguments);
var allArgs = args.concat(newArgs);
return fn.apply(this, allArgs);
}
}
function show(name, fruit, where) {
var msg = name + ' like ' + where + ' ' + fruit + '!';
console.log(msg);
return msg;
}
// the same output
curryHelper(show, 'Jarry')('apple', 'Hangzhou');
curryHelper(show, 'Jarry', 'apple')('Hangzhou');
curryHelper(show, 'Jarry', 'apple', 'Hangzhou')();
// the better curry
function betterCurry(fn, length) {
length = length || fn.length;
return function () {
var allArgumentsSpecified = (arguments.length >= length);
if (allArgumentsSpecified) {
return fn.apply(this, arguments);
}
console.log([fn], 1);
var partial = [fn].concat(Array.prototype.slice.call(arguments));
console.log(partial, 2);
return betterCurry(curryHelper.apply(this, partial), length - arguments.length);
};
}
betterCurry(show)('a')('b')('c');
betterCurry(show)('a', 'b')('c');
betterCurry(show)('a')('b', 'c');