forked from funjs/book-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chapter03.js
151 lines (112 loc) · 2.41 KB
/
chapter03.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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
function makeEmptyObject() {
return new Object();
}
var globals = {};
function makeBindFun(resolver) {
return function(k, v) {
var stack = globals[k] || [];
globals[k] = resolver(stack, v);
return globals;
};
}
var stackBinder = makeBindFun(function(stack, v) {
stack.push(v);
return stack;
});
var stackUnbinder = makeBindFun(function(stack) {
stack.pop();
return stack;
});
var dynamicLookup = function(k) {
var slot = globals[k] || [];
return _.last(slot);
};
function f() { return dynamicLookup('a'); };
function g() { stackBinder('a', 'g'); return f(); };
f();
//=> 1
g();
//=> 'g'
globals;
// {a: [1, "g"], b: [100]}
function strangeIdentity(n) {
// intentionally strange
for(var i=0; i<n; i++);
return i;
}
strangeIdentity(138);
//=> 138
function strangeIdentity(n) {
var i;
for(i=0; i<n; i++);
return i;
}
function strangerIdentity(n) {
// intentionally stranger still
for(this['i'] = 0; this['i']<n; this['i']++);
return this['i'];
}
strangerIdentity(108);
//=> 108
function createScaleFunction(FACTOR) {
return function(v) {
return _.map(v, function(n) {
return (n * FACTOR);
});
};
}
var scale10 = createScaleFunction(10);
scale10([1,2,3]);
//=> [10, 20, 30]
function createWeirdScaleFunction(FACTOR) {
return function(v) {
this['FACTOR'] = FACTOR;
var captures = this;
return _.map(v, _.bind(function(n) {
return (n * this['FACTOR']);
}, captures));
};
}
var scale10 = createWeirdScaleFunction(10);
scale10.call({}, [5,6,7]);
//=> [50, 60, 70];
function makeAdder(CAPTURED) {
return function(free) {
return free + CAPTURED;
};
}
var add10 = makeAdder(10);
add10(32);
//=> 42
function averageDamp(FUN) {
return function(n) {
return average([n, FUN(n)]);
}
}
var averageSq = averageDamp(function(n) { return n * n });
averageSq(10);
//=> 55
function complement(PRED) {
return function() {
return !PRED.apply(null, _.toArray(arguments));
};
}
function isEven(n) { return (n%2) === 0 }
var isOdd = complement(isEven);
isOdd(2);
//=> false
isOdd(413);
//=> true
function plucker(FIELD) {
return function(obj) {
return (obj && obj[FIELD]);
};
}
var best = {title: "Infinite Jest", author: "DFW"};
var getTitle = plucker('title');
getTitle(best);
//=> "Infinite Jest"
var books = [{title: "Chthon"}, {stars: 5}, {title: "Botchan"}];
var third = plucker(2);
third(books);
//=> {title: "Botchan"}