-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
570 lines (507 loc) · 19 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
560
561
562
563
564
565
566
567
568
569
570
/**
* (c) 2017 cepharum GmbH, Berlin, http://cepharum.de
*
* The MIT License (MIT)
*
* Copyright (c) 2017 cepharum GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author: cepharum
*/
"use strict";
/**
* @typedef {function( item:*, index:(number|string), collection:object):(Promise<*>|*)} IterationCallbackAny
*/
/**
* @typedef {function( item:*, index:(number|string), collection:object):(Promise<boolean>|boolean)} IterationCallbackBoolean
*/
/**
* Implements promise-related utility functions.
*/
class PromiseUtil {
/**
* Iterates over provided items invoking callback on each item waiting for
* callback to complete before advancing.
*
* @note This method is capable of handling array-like collections, too.
*
* @param {object} items collection of items to be traversed
* @param {IterationCallbackAny} fn callback invoked per item of collection
* @param {boolean} stopOnReturn set true or false to have iteration stop early on truthy/falsy return from callback
* @returns {Promise<object|boolean>} promises provided collection after its traversal, true on stopped early, false on stopping early enabled w/o occurring
*/
static each( items, fn, { stopOnReturn = null } = {} ) {
const { indexes, length, useGet } = prepareIteration( items );
return new Promise( function( resolve, reject ) {
step( items, indexes, 0, length );
/**
* Triggers processing of next available item.
*
* @param {object} collection collection to process
* @param {Array} keys list of indexes addressing items of collection
* @param {int} current index into list of indexes addressing current item
* @param {int} stopAt number of items in collection
* @returns {void}
*/
function step( collection, keys, current, stopAt ) {
if ( current < stopAt ) {
const key = keys ? keys[current] : current;
const item = useGet ? collection.get( key ) : collection[key];
let promise;
if ( item && item instanceof Promise ) {
promise = item.then( i => fn( i, key, collection ) );
} else {
promise = new Promise( done => done( fn( item, key, collection ) ) );
}
promise
.then( value => {
if ( stopOnReturn != null && value != null && Boolean( value ) === stopOnReturn ) {
resolve( true );
} else {
process.nextTick( step, collection, keys, current + 1, stopAt );
}
} )
.catch( reject );
} else {
resolve( stopOnReturn == null ? collection : false );
}
}
} );
}
/**
* Iterates over collection looking for at least one item satisfying given
* callback by means of causing it to return truthy value.
*
* @param {object} items collection of items to traverse
* @param {IterationCallbackBoolean} fn callback invoked per item, returns truthy value if item is satisfying
* @returns {Promise<boolean>} promises true if at least one item of collection was satisfying callback, false otherwise
*/
static some( items, fn ) {
return this.each( items, fn, { stopOnReturn: true } );
}
/**
* Iterates over collection checking if every item is satisfying provided
* callback by means of causing it to return truthy value on every item.
*
* @param {object} items collection of items to traverse
* @param {IterationCallbackBoolean} fn callback invoked per item, returns truthy value if item is satisfying
* @returns {Promise<boolean>} promises true if every item of collection was satisfying callback, false otherwise
*/
static every( items, fn ) {
return this.each( items, fn, { stopOnReturn: false } ).then( result => !result );
}
/**
* Iterates over array of items invoking provided callback on each item and
* copying every item with callback returning truthy result into new array which
* is promised eventually.
*
* @note This method is capable of handling array-like collections, too.
*
* @param {object} items collection of items to filter
* @param {IterationCallbackAny} fn callback invoked per item of collection
* @param {boolean} asArray set true to always fetch an array of kept items, set false to get collection matching provided one by type
* @returns {Promise<object>} promised collection of filtered items
*/
static filter( items, fn, { asArray = true } = {} ) {
const { indexes, length, useGet, collector } = prepareIteration( items, { createCollector: true, asArray } );
return new Promise( function( resolve, reject ) {
step( items, indexes, 0, length, collector, 0 );
/**
* Triggers processing of next available item.
*
* @param {object} collection collection of items
* @param {Array} keys list of indexes addressing items of collection
* @param {int} current offset of index addressing current item
* @param {int} numItems number of items in collection
* @param {object} result collector for items to keep
* @param {int} writeIndex next item in a sequential collector to write
* @returns {void}
*/
function step( collection, keys, current, numItems, result, writeIndex ) {
if ( current < numItems ) {
const key = keys ? keys[current] : current;
const item = useGet ? collection.get( key ) : collection[key];
let promise;
if ( item instanceof Promise ) {
promise = item.then( i => fn( i, key, collection ) );
} else {
promise = new Promise( done => done( fn( item, key, collection ) ) );
}
promise
.then( keep => {
let _writeIndex = writeIndex;
if ( keep ) {
if ( result instanceof Map ) {
result.set( key, item );
} else if ( Array.isArray( result ) ) {
result[_writeIndex++] = item;
} else {
result[key] = item;
}
}
process.nextTick( step, collection, keys, current + 1, numItems, result, _writeIndex );
} )
.catch( reject );
} else {
if ( Array.isArray( result ) ) {
result.splice( writeIndex, numItems - writeIndex );
}
resolve( result );
}
}
} );
}
/**
* Iterates over array of items invoking provided callback on each item and
* copying result provided by callback into new array promised eventually.
*
* @note This method is capable of handling array-like collections, too.
*
* @param {object} items collection of items to map
* @param {IterationCallbackAny} fn callback invoked per item for provided mapped value
* @param {boolean} asArray set true to always fetch an array of kept items, set false to get collection matching provided one by type
* @returns {Promise<object>} promised collection of mapped items
*/
static map( items, fn, { asArray = true } = {} ) {
const { indexes, length, useGet, collector } = prepareIteration( items, { createCollector: true, asArray } );
return new Promise( function( resolve, reject ) {
step( items, indexes, 0, length, collector );
/**
* Triggers processing of next available item.
*
* @param {object} collection collection of items to process
* @param {string[]} keys lists keys of items in collection
* @param {int} current index into list of keys addressing current item to process
* @param {int} numItems number of items in collection
* @param {object} result separate instance matching collection by type, fed with mapped value per item
* @returns {void}
*/
function step( collection, keys, current, numItems, result ) {
if ( current < numItems ) {
const key = keys ? keys[current] : current;
const item = useGet ? collection.get( key ) : collection[key];
let promise;
if ( item instanceof Promise ) {
promise = item.then( value => fn( value, key, collection ) );
} else {
promise = new Promise( done => done( fn( item, key, collection ) ) );
}
promise
.then( mappedValue => {
if ( result instanceof Map ) {
result.set( key, mappedValue );
} else if ( Array.isArray( result ) ) {
result[current] = mappedValue;
} else {
result[key] = mappedValue;
}
process.nextTick( step, collection, keys, current + 1, numItems, result );
} )
.catch( reject );
} else {
resolve( result );
}
}
} );
}
/**
* Maps all provided items onto values provided some callback invoked on every
* item and returning Promise resolved with all mapped items.
*
* This method is processing all mappings simultaneously and waits for all
* started mappings to complete before promising result.
*
* @note This method is capable of handling array-like collections, too.
*
* @param {object} items collection of items to map
* @param {IterationCallbackAny} fn callback invoked per item
* @param {boolean} asArray set true to always fetch an array of kept items, set false to get collection matching provided one by type
* @returns {Promise<object>} promised collection of mapped items
*/
static multiMap( items, fn, { asArray = true } = {} ) {
const { indexes, length, useGet, collector } = prepareIteration( items, { createCollector: true, asArray } );
const mapping = new Array( length );
for ( let index = 0; index < length; index++ ) {
const key = indexes ? indexes[index] : index;
const item = useGet ? items.get( key ) : items[key];
( ( _item, _key, _index ) => {
if ( _item instanceof Promise ) {
mapping[_index] = _item.then( i => fn( i, _key, items ) );
} else {
mapping[_index] = new Promise( resolve => resolve( fn( _item, _key, items ) ) );
}
} )( item, key, index );
}
return Promise.all( mapping )
.then( mappedValues => {
if ( Array.isArray( collector ) ) {
return mappedValues;
}
if ( collector instanceof Map ) {
for ( let i = 0; i < length; i++ ) {
collector.set( indexes[i], mappedValues[i] );
}
} else {
for ( let i = 0; i < length; i++ ) {
collector[indexes[i]] = mappedValues[i];
}
}
return collector;
} );
}
/**
* Iterates over array of items invoking provided callback on each item stopping
* iteration on first item callback is returning truthy value.
*
* @note This method is capable of handling array-like collections, too.
*
* @param {object} items collection of items to search
* @param {IterationCallbackBoolean} fn callback invoked per item to identify the one to be found
* @param {boolean} getLast set true to get last match instead of first one
* @returns {Promise<*>} promises first element callback returned truthy on or
* undefined if no item satisfies this
*/
static find( items, fn, { getLast = false } = {} ) {
return this.indexOf( items, fn, { getLast } )
.then( index => {
if ( Array.isArray( items ) ) {
return index > -1 ? items[index] : undefined;
}
if ( index === undefined ) {
return undefined;
}
return items instanceof Map ? items.get( index ) : items[index];
} );
}
/**
* Iterates over collection of items invoking provided callback on each item
* stopping iteration on first item callback is returning truthy value.
*
* @note This method is capable of handling array-like collections, too.
*
* @param {Array} items array of items to filter
* @param {IterationCallbackBoolean} fn callback invoked per item to test if it's searched one
* @param {boolean} getLast set true to get index of last match instead of first one
* @returns {Promise<number>} promises index of first element callback returned
* truthy on or -1 if no item satisfies this
*/
static indexOf( items, fn, { getLast = false } = {} ) {
const { indexes, length, useGet } = prepareIteration( items );
return new Promise( function( resolve, reject ) {
step( items, indexes, getLast ? length - 1 : 0, getLast ? -1 : length, getLast ? -1 : +1 );
/**
* Triggers processing of next available item.
*
* @param {Array} collection collection of items
* @param {Array} keys list of keys addressing items of collection
* @param {int} current index into list of keys selecting current item's keys
* @param {int} numItems number of items in collection
* @param {int} advanceBy control direction of iteration: +1 to iterate forwardly, -1 otherwise
* @returns {void}
*/
function step( collection, keys, current, numItems, advanceBy ) {
if ( current === numItems ) {
resolve( keys ? undefined : -1 );
} else {
const key = keys ? keys[current] : current;
const item = useGet ? collection.get( key ) : collection[key];
let promise;
if ( item instanceof Promise ) {
promise = item.then( i => fn( i, key, collection ) );
} else {
promise = new Promise( done => done( fn( item, key, collection ) ) );
}
promise
.then( result => {
if ( result ) {
resolve( key );
} else {
process.nextTick( step, collection, keys, current + advanceBy, numItems, advanceBy );
}
} )
.catch( reject );
}
}
} );
}
/**
* Conveniently creates promise resolved with value after some delay.
*
* @param {number} delay desired delay in milliseconds
* @param {*=} payload value promise is fulfilled with
* @returns {Promise<*>} promised delay
*/
static delay( delay, payload ) {
return new Promise( resolve => setTimeout( resolve, delay, payload ) );
}
/**
* Asynchronously processes objects or chunks read from provided stream.
*
* @note This method is invoking provided function on every chunk or object read
* from stream. If provided function is throwing exception or returning
* eventually rejected promise the whole processing is aborted rejecting
* promise returned here as well.
*
* @note Stream is resumed initially and paused/resumed when invoked function
* has returned promise. **The stream is kept paused on processing item
* failed.**
*
* @param {Readable} stream stream to read objects or chunks from
* @param {function(this:object, current:*, index:number, stream:Readable):(Promise|*)} fn worker invoked to process every read chunk/object
* @returns {Promise<object>} promises object provided as `this` on invoking function per chunk/object read from stream
*/
static process( stream, fn = defaultProcessor ) {
return new Promise( ( resolve, reject ) => {
let counter = 0;
const target = {};
let finished = false;
let failure = null;
stream
.on( "data", step )
.on( "error", error => {
failure = error;
// don't immediately reject promise when callback is still
// processing item
if ( !stream.isPaused() ) {
reject( error );
}
} )
.on( "end", () => {
finished = true;
// don't immediately resolve promise when callback is still
// processing item
if ( !stream.isPaused() ) {
resolve( target );
}
} );
stream.resume();
/**
* Processes next available item.
*
* @node This method is pausing stream to ensure elements are processed
* sequentially.
*
* @param {Buffer|object} item or chunk item to be processed
* @returns {void}
*/
function step( item ) {
try {
const result = fn.call( target, item, counter++, stream );
if ( result instanceof Promise ) {
stream.pause();
result
.then( () => {
stream.resume();
if ( finished ) {
resolve( target );
} else if ( failure ) {
reject( failure );
}
} )
.catch( reject );
}
} catch ( exception ) {
stream.pause();
reject( exception );
}
}
} );
}
/**
* Wraps asynchronous function accepting node-style callback in a promise.
*
* @param {function} fn function to be promisified
* @param {object} bindTo context for binding given function to on invocation
* @returns {function():Promise} returns provided function returning Promise instead of using node-style callback
*/
static promisify( fn, bindTo = undefined ) {
return function( ...args ) {
const length = args.length;
const copy = new Array( length + 1 );
for ( let i = 0; i < length; i++ ) {
copy[i] = args[i];
}
return new Promise( ( resolve, reject ) => {
copy[length] = ( error, result ) => {
if ( error ) {
reject( error );
} else {
resolve( result );
}
};
fn.apply( bindTo === undefined ? this : bindTo, copy );
} );
};
}
}
module.exports = PromiseUtil;
/**
* Prepares sequential list of keys for successively iterating over elements of
* a given collection.
*
* @param {object} items collection to be iterated
* @param {boolean} createCollector set true to get an empty collector
* @param {boolean} asArray set true to always array as collector, otherwise it's an empty collector matching provided set of items by type
* @returns {{indexes: (?Array<string>), length:int, useGet:boolean, collector:object}} prepared iteration context and parameters
*/
function prepareIteration( items, { createCollector = false, asArray = false } = {} ) {
let indexes, length, useGet = false, collector = null;
if ( items instanceof Map ) {
useGet = true;
length = items.size;
indexes = new Array( length );
let index = 0;
for ( const key of items.keys() ) {
indexes[index++] = key;
}
if ( createCollector ) {
collector = asArray ? new Array( length ) : new Map();
}
} else if ( Array.isArray( items ) || ( items.length > -1 && parseInt( items.length ) === parseFloat( items.length ) ) ) {
// prepare for iterating over indexes of array or array-like collection
length = items.length;
indexes = null;
if ( createCollector ) {
collector = new Array( length );
}
} else if ( typeof items === "object" ) {
// prepare for iterating over properties of object
indexes = Object.keys( items );
length = indexes.length;
if ( createCollector ) {
collector = asArray ? new Array( length ) : {};
}
} else {
throw new TypeError( "non-iterable collection rejected" );
}
return { indexes, length, useGet, collector };
}
/**
* Collects another item in array optionally created at `this.collected`.
*
* @param {object|Buffer} item some item/chunk read from stream to be processed
* @returns {void}
*/
function defaultProcessor( item ) {
if ( !this.collected ) {
this.collected = [];
}
this.collected.push( item );
}