-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.js
113 lines (93 loc) · 2.8 KB
/
utils.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
/*!
* each-promise <https://github.com/tunnckoCore/each-promise>
*
* Copyright (c) Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
* Released under the MIT license.
*/
'use strict'
var register = require('native-or-another/register')
var Promize = require('native-or-another')
var extendShallow = require('extend-shallow')
var redolent = require('redolent')
var utils = {}
utils.extend = extendShallow
utils.promisify = redolent
utils.defaults = function defaults (mapper, opts) {
var options = null
if (mapper && typeof mapper === 'object') {
options = mapper
mapper = null
}
options = utils.extend({}, options, opts)
options = utils.extend({
Promise: Promize,
settle: true,
flat: true,
serial: false,
concurrency: false,
start: function startHook () {},
beforeEach: function beforeEachHook () {},
afterEach: function afterEachHook () {},
finish: function finishHook () {}
}, options)
options.Promise = register({ Promise: options.Promise, 'global': false })
mapper = options.mapper || mapper
options.mapper = typeof mapper === 'function' ? mapper : false
return options
}
utils.iterator = function iterator (arr, results) {
return function (options, resolve, reject) {
return function next (index) {
if (index >= arr.length) {
return
}
var item = arr[index]
options.beforeEach({ value: item, index: index }, index, arr)
var promise = typeof item === 'function'
? utils.promisify(item, options)()
: utils.promisify(function () { return item }, options)()
var handle = utils.handleResults({
arr: arr,
index: index,
results: results
}, options)
var onRejected = options.settle === false ? function onrejected (err) {
options.finish(err, results)
reject(err)
} : null
promise.then(handle('value'), handle('reason'))
.catch(onRejected)
.then(function onresolved () {
if (arr.doneCount++ === arr.length - 1) {
options.finish(null, results)
resolve(results)
return
}
next(index + options.concurrency)
})
.catch(onRejected)
}
}
}
utils.handleResults = function handleResults (config, options) {
return function handle (name) {
return function handler (val) {
var ret = {}
ret[name] = val
ret.index = config.index
options.afterEach(ret, ret.index, config.arr)
if (typeof options.mapper === 'function') {
config.results.push(options.mapper(ret, ret.index, config.arr))
return
}
config.results.push(options.flat ? ret[name] : ret)
if (options.settle === false && ret.reason) {
throw val
}
}
}
}
/**
* Expose `utils` module
*/
module.exports = utils