forked from funjs/book-source
-
Notifications
You must be signed in to change notification settings - Fork 1
/
5.js
317 lines (236 loc) · 6.62 KB
/
5.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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
function dispatch(/* funs */) {
var funs = _.toArray(arguments);
var size = funs.length;
return function(target /*, args */) {
var ret = undefined;
var args = _.rest(arguments);
for (var funIndex = 0; funIndex < size; funIndex++) {
var fun = funs[funIndex];
ret = fun.apply(fun, construct(target, args));
if (existy(ret)) return ret;
}
return ret;
};
}
var str = dispatch(invoker('toString', Array.prototype.toString),
invoker('toString', String.prototype.toString));
str("a");
//=> "a"
str(_.range(10));
//=> "0,1,2,3,4,5,6,7,8,9"
function stringReverse(s) {
if (!_.isString(s)) return undefined;
return s.split('').reverse().join("");
}
stringReverse("abc");
//=> "cba"
stringReverse(1);
//=> undefined
var rev = dispatch(invoker('reverse', Array.prototype.reverse),
stringReverse);
rev([1,2,3]);
//=> [3, 2, 1]
rev("abc");
//=> "cba"
function performCommandHardcoded(command) {
var result;
switch (command.type)
{
case 'notify':
result = notify(command.message);
break;
case 'join':
result = changeView(command.target);
break;
default:
alert(command.type);
}
return result;
}
function isa(type, action) {
return function(obj) {
if (type === obj.type)
return action(obj);
}
}
var performCommand = dispatch(
isa('notify', function(obj) { return notify(obj.message) }),
isa('join', function(obj) { return changeView(obj.target) }),
function(obj) { alert(obj.type) });
var performAdminCommand = dispatch(
isa('kill', function(obj) { return shutdown(obj.hostname) }),
performCommand);
var performTrialUserCommand = dispatch(
isa('join', function(obj) { alert("Cannot join until approved") }),
performCommand);
function rightAwayInvoker() {
var args = _.toArray(arguments);
var method = args.shift();
var target = args.shift();
return method.apply(target, args);
}
rightAwayInvoker(Array.prototype.reverse, [1,2,3])
//=> [3, 2, 1]
function leftCurryDiv(n) {
return function(d) {
return n/d;
};
}
function rightCurryDiv(d) {
return function(n) {
return n/d;
};
}
function curry(fun) {
return function(arg) {
return fun(arg);
};
}
function curry2(fun) {
return function(secondArg) {
return function(firstArg) {
return fun(firstArg, secondArg);
};
};
}
function div(n, d) { return n / d }
var div10 = curry2(div)(10);
div10(50);
//=> 5
var parseBinaryString = curry2(parseInt)(2);
parseBinaryString("111");
//=> 7
parseBinaryString("10");
//=> 2
var plays = [{artist: "Burial", track: "Archangel"},
{artist: "Ben Frost", track: "Stomp"},
{artist: "Ben Frost", track: "Stomp"},
{artist: "Burial", track: "Archangel"},
{artist: "Emeralds", track: "Snores"},
{artist: "Burial", track: "Archangel"}];
_.countBy(plays, function(song) {
return [song.artist, song.track].join(" - ");
});
//=> {"Ben Frost - Stomp": 2,
// "Burial - Archangel": 3,
// "Emeralds - Snores": 1}
function songToString(song) {
return [song.artist, song.track].join(" - ");
}
var songCount = curry2(_.countBy)(songToString);
songCount(plays);
//=> {"Ben Frost - Stomp": 2,
// "Burial - Archangel": 3,
// "Emeralds - Snores": 1}
function curry3(fun) {
return function(last) {
return function(middle) {
return function(first) {
return fun(first, middle, last);
};
};
};
};
var songsPlayed = curry3(_.uniq)(false)(songToString);
songsPlayed(plays);
//=> [{artist: "Burial", track: "Archangel"},
// {artist: "Ben Frost", track: "Stomp"},
// {artist: "Emeralds", track: "Snores"}]
function toHex(n) {
var hex = n.toString(16);
return (hex.length < 2) ? [0, hex].join(''): hex;
}
function rgbToHexString(r, g, b) {
return ["#", toHex(r), toHex(g), toHex(b)].join('');
}
rgbToHexString(255, 255, 255);
//=> "#ffffff"
var blueGreenish = curry3(rgbToHexString)(255)(200);
blueGreenish(0);
//=> "#00c8ff"
var greaterThan = curry2(function (lhs, rhs) { return lhs > rhs });
var lessThan = curry2(function (lhs, rhs) { return lhs < rhs });
var withinRange = checker(
validator("arg must be greater than 10", greaterThan(10)),
validator("arg must be less than 20", lessThan(20)));
function divPart(n) {
return function(d) {
return n / d;
};
}
var over10Part = divPart(10);
over10Part(2);
//=> 5
function partial1(fun, arg1) {
return function(/* args */) {
var args = construct(arg1, arguments);
return fun.apply(fun, args);
};
}
function partial2(fun, arg1, arg2) {
return function(/* args */) {
var args = cat([arg1, arg2], arguments);
return fun.apply(fun, args);
};
}
var div10By2 = partial2(div, 10, 2)
div10By2()
//=> 5
function partial(fun /*, pargs */) {
var pargs = _.rest(arguments);
return function(/* arguments */) {
var args = cat(pargs, _.toArray(arguments));
return fun.apply(fun, args);
};
}
var zero = validator("cannot be zero", function(n) { return 0 === n
});
var number = validator("arg must be a number", _.isNumber);
function sqr(n) {
if (!number(n)) throw new Error(number.message);
if (zero(n)) throw new Error(zero.message);
return n * n;
}
function condition1(/* validators */) {
var validators = _.toArray(arguments);
return function(fun, arg) {
var errors = mapcat(function(isValid) {
return isValid(arg) ? [] : [isValid.message];
}, validators);
if (!_.isEmpty(errors))
throw new Error(errors.join(", "));
return fun(arg);
};
}
var sqrPre = condition1(
validator("arg must not be zero", complement(zero)),
validator("arg must be a number", _.isNumber));
function uncheckedSqr(n) { return n * n };
uncheckedSqr('');
//=> 0
var checkedSqr = partial1(sqrPre, uncheckedSqr);
var sillySquare = partial1(
condition1(validator("should be even", isEven)),
checkedSqr);
var validateCommand = condition1(
validator("arg must be a map", _.isObject),
validator("arg must have the correct keys", hasKeys('msg',
'type')));
var createCommand = partial(validateCommand, _.identity);
var createLaunchCommand = partial1(
condition1(
validator("arg must have the count down", hasKeys('countDown'))),
createCommand);
var isntString = _.compose(function(x) { return !x }, _.isString);
isntString([]);
//=> true
function not(x) { return !x }
var composedMapcat = _.compose(splat(cat), _.map);
composedMapcat([[1,2],[3,4],[5]], _.identity);
//=> [1, 2, 3, 4, 5]
var sqrPost = condition1(
validator("result should be a number", _.isNumber),
validator("result should not be zero", complement(zero)),
validator("result should be positive", greaterThan(0)));
var megaCheckedSqr = _.compose(partial(sqrPost, _.identity),
checkedSqr);