-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
559 lines (520 loc) · 14.7 KB
/
index.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//. # bluebird-promisell
//. A functional programming library for promises.
//.
//. `bluebird-promisell` provides a set of composable functions that allows you to write flat async code with promises.
//.
//. ## Usage
//. ### Write flat async code with "liftp"
//.
//. Let's say we have the following sync code to get a list of userId.
//.
//. ```javascript
//. var getToken = function() { return 'token'; };
//. var getSecret = function() { return 'secret'; };
//. var getUserIds = function(token, secret) {
//. return [1, 2, 3];
//. };
//.
//. // Token
//. var token = getToken();
//.
//. // Secret
//. var secret = getSecret();
//.
//. // [UserId]
//. var userIds = getUserIds(token, secret);
//.
//. console.log(userIds); // [1, 2, 3]
//. ```
//.
//. Now, if the sub functions `getToken`, `getSecret`, `getUserIds` becomes async (all return Promise),
//. the only change we need to make is "lifting" `getUserIds` with `liftp`.
//.
//. ```javascript
//. var Promise = require('bluebird');
//. var P = require('bluebird-promisell');
//.
//. var getToken = function() { return Promise.resolve('token'); };
//. var getSecret = function() { return Promise.resolve('secret'); };
//. var getUserIds = function(token, secret) {
//. return Promise.resolve([1, 2, 3]);
//. };
//.
//. // Promise Token
//. var tokenP = getToken();
//.
//. // Promise Secret
//. var secretP = getSecret();
//.
//. // Promise [UserId]
//. var userIdsP = P.liftp(getUserIds)(tokenP, secretP);
//.
//. userIdsP.then(console.log); // [1, 2, 3]
//. ```
//.
//. Now the code runs async, but it reads like sync code.
//.
//. ### Making async calls in parallel with "traversep"
//.
//. ```javascript
//. var getPhotoByUserId = function(userId) {
//. if (userId === 1) {
//. return ':)';
//. } else if (userId === 2) {
//. return ':D';
//. } else {
//. return ':-|';
//. }
//. };
//.
//. // Promise Token
//. var tokenP = getToken();
//.
//. // Promise Secret
//. var secretP = getSecret();
//.
//. // Promise [UserId]
//. var userIdsP = P.liftp(getUserIds)(tokenP, secretP);
//.
//. // Promise [Photo]
//. var photosP = P.traversep(getPhotoByUserId)(userIdsP);
//. photosP.then(console.log); // [":)", ":D", ":-|"]
//. ```
//.
//. ### Making async calls sequentially with "foldp"
//. ```javascript
//. // Promise [UserId]
//. var userIdsP = P.liftp(getUserIds)(tokenP, secretP);
//.
//. // [Photo] -> Photo -> [Photo]
//. var appendPhotos = function(photos, photo) {
//. return photos.concat([photo]);
//. };
//.
//. // Promise [Photo]
//. var photosP = P.foldp(function(photos, userId) {
//. // Promise Photo
//. var photoP = getPhotoByUserId(userId);
//. return P.liftp(appendPhotos)(P.purep(photos), photoP); // `P.purep` is equivalent to `Promise.resolve`
//. })([])(userIdsP);
//.
//. photosP.then(console.log); // [":)", ":D", ":-|"]
//. ```
//.
//. The above code will fetch photo by userId sequentially. If it fails to fetch the first photo,
//. it will reject the promise without fetching next photo.
//. And it will resolve the promise once all the photos have been fetched.
//.
//. ## Wait until the second async call to finish, then return the value of the first async call
//.
//. Let's say we want to send an email with all the photos, and wait until the email has been sent,
//. then resolve the promise with the photos
//.
//. With `firstp`, we can wait until the email has been sent, and return the result of photos which
//. is from the first promise.
//
//. ```javascript
//. var sendEmailWithPhotos = function(photos) {
//. return Promise.resolve('The email has been sent');
//. };
//.
//. // Promise [Photo]
//. var photosP = P.foldp(function(photos, userId) {
//. // Promise Photo
//. var photoP = getPhotoByUserId(userId);
//. return P.liftp(appendPhotos)(P.purep(photos), photoP); // `P.purep` is equivalent to `Promise.resolve`
//. })([])(userIdsP);
//.
//. // Promise String
//. var sentP = P.liftp1(sendEmailWithPhotos)(photosP);
//. // ^^^^^^^^ P.liftp1 is equivalent to P.liftp when there is only one promise to resolve.
//. // But P.liftp1 has better performance than P.liftp.
//.
//. P.first(photosP, sentP).then(console.log); // [":)", ":D", ":-|"]
//. ```
//.
//. ## API
//# purep :: a -> Promise a
//.
//. Takes any value, returns a resolved Promise with that value
//.
//. ```js
//. > purep(3).then(console.log)
//. promise
//. 3
//. ```
'use strict';
var Promise = require('bluebird');
// a -> String
var getType = function(val) {
return val === null ? 'Null' :
val === undefined ? 'Undefined' :
Object.prototype.toString.call(val).slice(8, -1);
};
// String -> String -> a -> a
var assertType = function(expectedType, value) {
var actualType = getType(value);
if (expectedType!== actualType) {
throw new TypeError('Expected type to be ' +
expectedType + ', but got ' + actualType);
}
return value;
};
exports.purep = function(a) {
return Promise.resolve(a);
};
exports.reject = Promise.reject;
var noop = function() { };
// apply :: (a -> b ... -> n -> x) -> [a, b ... n] -> x
var apply = function(fn) {
return function(args) {
return fn.apply(this, args);
};
};
// id :: a -> a
var id = function(a) {
return a;
};
var slice = Array.prototype.slice;
var toArray = function(a) {
return slice.call(a);
};
var fold = function(iter, initial, arr) {
if (!arr.length) {
return initial;
}
var newInitial = iter(initial, arr[0]);
return fold(iter, newInitial, slice.call(arr, 1));
};
var map = function(f) {
return function(arr) {
return fold(function(memo, item) {
return memo.concat([f(item)]);
}, [], arr);
};
};
var pipe = function() {
var fns = toArray(arguments);
return function(a) {
return fold(function(acc, fn) {
return fn(acc);
}, a, fns);
};
};
var liftp1 = function(fn) {
assertType('Function', fn);
return function(p) {
return p.then(fn);
};
};
//# fmapp :: (a -> b) -> Promise a -> Promise b
//
//. Transforms a Promise of value a into a Promise of value b
//
//. ```js
//. > fmapp(function(a) { return a + 3; }, Promise.resolve(4)).then(console.log)
//. promise
//. 7
//. ```
exports.fmapp = liftp1;
//# voidp :: Promise a -> Promise undefined
//
//. Takes a Promise, returns a Promise that resolves with undefined when the input promise is resolved,
//. or reject with the same error when the input promise is rejected.
//
//. ```js
//. > voidp(purep(12)).then(console.log)
//. promise
//. undefined
//. ```
exports.voidp = liftp1(noop);
//# sequencep :: Array Promise a -> Promise Array a
//
//. Transforms an array of Promise of value a into a Promise of array of a.
//
//. ```js
//. > sequencep([Promise.resolve(3), Promise.resolve(4)]).then(console.log)
//. promise
//. [3, 4]
//. ```
exports.sequencep = function(arr) {
assertType('Array', arr);
return Promise.all(arr);
};
//# traversep :: (a -> Promise b) -> Array a -> Promise Array b
//
//. Maps a function that takes a value a and returns a Promise of value b over an array of value a,
//. then use `sequencep` to transform the array of Promise b into a Promise of array b
//
//. ```js
//. > traversep(function(a) { return Promise.resolve(a + 3); })(
//. [2, 3, 4])
//. promise
//. [5, 6, 7]
//. ```
exports.traversep = function(fn) {
assertType('Function', fn);
return pipe(map(fn), exports.sequencep);
};
//# pipep :: [(a -> Promise b), (b -> Promise c), ... (m -> Promise n)] -> a -> Promise n
//
//. Performs left-to-right composition of an array of Promise-returning functions.
//
//. ```js
//. > pipep([
//. function(a) { return Promise.resolve(a + 3); },
//. function(b) { return Promise.resolve(b * 10); },
//. ])(6);
//. promise
//. 90
//. ```
exports.pipep = function(pipes) {
assertType('Array', pipes);
return function(a) {
return fold(function(accp, fn) {
return accp.then(fn);
}, exports.purep(a), pipes);
};
};
//# liftp :: (a -> b -> ... n -> x) -> Promise a -> Promise b -> ... -> Promise n -> Promise x
//
//. Takes a function so that this function is able to read input values from resolved Promises,
//. and return a Promise that will resolve with the output value of that function.
//
//. ```js
//. > liftp(function(a, b, c) { return (a + b) * c; })(
//. Promise.resolve(3),
//. Promise.resolve(4),
//. Promise.resolve(5));
//. promise
//. 35
//. ```
exports.liftp = function(fn) {
assertType('Function', fn);
return function() {
return exports.fmapp(apply(fn))(exports.sequencep(toArray(arguments)));
};
};
//# liftp1 :: (a -> b) -> Promise a -> Promise b
//
//. Takes a function and apply this function to the resolved Promise value, and return
//. a Promise that will resolve with the output of that function.
//
//. ```js
//. > liftp1(function(user) {
//. return user.email;
//. })(Promise.resolve({ email: 'abc@example.com' }));
//. promise
//. abc@example.com
//. ```
exports.liftp1 = liftp1;
exports.liftp2 = exports.liftp3 = exports.liftp4 = exports.liftp5 = exports.liftp;
//# firstp :: Promise a -> Promise b -> Promise a
//
//. Takes two Promises and return the first if both of them are resolved
//
//. ```js
//. > firstp(Promise.resolve(1), Promise.resolve(2))
//. promise
//. 1
//
//. > firstp(Promise.resolve(1), Promise.reject(new Error(3)))
//. promise
//. Error 3
//. ```
exports.firstp = exports.liftp(id);
var second = function(a, b) { return b; };
//# secondp :: Promise a -> Promise b -> Promise b
//
//. Takes two Promises and return the second if both of them are resolved
//
//. ```js
//. > secondp(Promise.resolve(1), Promise.resolve(2))
//. promise
//. 2
//
//. > secondp(Promise.resolve(1), Promise.reject(new Error(3)))
//. promise
//. Error 3
//. ```
exports.secondp = exports.liftp(second);
//# filterp :: (a -> Promise Boolean) -> Array a -> Promise Array a
//
//. Takes a predicat that returns a Promise and an array of a, returns a Promise of array a
//. which satisfy the predicate.
//
//. ```js
//. > filterp(function(a) { return Promise.resolve(a > 3); })([2, 3, 4])
//. promise
//. [4]
//. ```
exports.filterp = function(predictp) {
return function(xs) {
return Promise.filter(xs, predictp);
};
};
//# foldp :: (b -> a -> Promise b) -> b -> Array a -> Promise b
//
//. Returns a Promise of value b by iterating over an array of value a, successively
//. calling the iterator function and passing it an accumulator value of value b,
//. and the current value from the array, and then waiting until the promise resolved,
//. then passing the result to the next call.
//.
//. foldp resolves promises sequentially
//
//. ```js
//. > foldp(function(b, a) { return Promise.resolve(b + a); })(1)([2, 3, 4])
//. promise
//. 10
//. ```
exports.foldp = function(fn) {
return function(init) {
return function(arr) {
if (!arr.length) {
return exports.purep(init);
}
return fn(init, arr[0]).then(function(b) {
return exports.foldp(fn)(b)(slice.call(arr, 1));
});
};
};
};
var loop = function(fn, init, seed) {
return fn(init, seed).then(function(result) {
assertType('Array', result);
if (result[1] === null) {
return result[0];
} else {
return loop(fn, result[0], result[1]);
}
});
};
var _unfold = function(fn) {
return function(init) {
return function(seed) {
return loop(fn, init, seed);
};
};
};
//# unfold :: (a -> Promise [b, a]?) -> a -> Promise [b]
//
//. Builds a list from a seed value. Accepts an iterator function, which takes the seed and return a Promise.
//. If the Promise resolves to a `false` value, it will return the list.
//. If the Promise resolves to a pair, the first item will be appended to the list and the second item will be used as the new seed in the next call to the iterator function.
//
//. ```js
//. > unfold(function(a) {
//. return a > 5 ? Promise.resolve(false) : Promise.resolve([a, a + 1]);
//. })(1);
//. promise
//. [1,2,3,4,5]
//. ```
exports.unfold = exports.unfoldp = function(fn) {
return function(seed) {
return _unfold(function(accum, s) {
return fn(s)
.then(function(result) {
return result === false ? [accum, null]
: [accum.concat(result[0]), result[1]];
});
})([])(seed);
};
};
//# mapError :: (Error -> Error) -> Promise a -> Promise a
//
//. Transform the rejected Error.
//
//. ```js
//. > mapError(function(err) {
//. var newError = new Error(err.message);
//. newError.status = 400;
//. return newError;
//. })(Promise.reject(new Error('Not Found')));
//. rejected promise
//. ```
exports.mapError = function(fn) {
return function(p) {
return p.catch(function(error) {
var newError = fn(error);
return Promise.reject(newError);
});
};
};
//# resolveError :: (Error -> b) -> Promise a -> Promise b
//
//. Recover from a rejected Promise
//
//. ```js
//. > resolveError(function(err) {
//. return false;
//. });
//. ```
//. promise
//. false
exports.resolveError = function(fn) {
return function(p) {
return p.catch(fn);
};
};
//# toPromise :: ((a -> Boolean), (a -> Error)) -> a -> Promise a
//
//. Takes a `predict` function and a `toError` function, return a curried
//. function that can take a value and return a Promise.
//. If this value passes the predict, then return a resolved Promise with
//. that value, otherwise pass the value to the `toError` function, and
//. return a rejected Promise with the output of the `toError` function.
//
//. ```js
//. var validateGreaterThan0 = toPromise(function(a) {
//. return a > 0;
//. }, function(a) {
//. return new Error('value is not greater than 0');
//. });
//
//. > validateGreaterThan0(10)
//. promise
//. 10
//.
//. > validateGreaterThan0(-10)
//. rejected promise
//. Error 'value is not greater than 0'
//. ```
exports.toPromise = function(predict, toError) {
return function(a) {
var valid = predict(a);
if (valid) {
return Promise.resolve(a);
} else {
return Promise.reject(toError(a));
}
};
};
//# bimap :: (a -> Promise b) -> (Error -> Promise b) -> Promise a -> Promise b
//
//. Takes two functions and return a function that can take a Promise and return a Promise.
//. If the received Promise is resolved, the first function will be used to map over the resolved value;
//. If the received Promise is rejected, the second function will be used to map over the Error.
//.
//. Like Promise.prototype.then function, but takes functions first.
//.
//. ```js
//. var add1OrReject = bimap(
//. function(n) { return n + 1; },
//. function(error) {
//. return new Error('can not add value for ' + error.message);
//. }
//. );
//.
//. > add1OrReject(P.purep(2))
//. promise
//. 3
//.
//. > add1OrReject(Promise.reject(new Error('NaN')));
//. promise
//. 'can not add value for NaN'
//. ```
exports.bimap = function(mapResolved, mapError) {
return function(p) {
return p.then(mapResolved, mapError);
};
};