-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
105 lines (88 loc) · 2.51 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
/**
* Dillon Bostwick
*/
const _ = require('lodash');
const async = require('async');
const defaultOptions = {
includeLeaves: true,
includeBranches: false,
parallel: true
};
const handleInput = (rootObj, iteratee, options, done) => {
if (_.isUndefined(rootObj) || (!_.isFunction(iteratee) && !(iteratee instanceof Promise))) {
throw new TypeError('Must pass rootObj and iteratee')
}
if (options && _.isObject(options)) {
_.each(options, (option) => {
if (!_.isBoolean(option)) {
throw new TypeError('All options should be boolean')
}
})
_.defaults(options, defaultOptions)
} else {
options = defaultOptions
}
if (!_.isUndefined(done)) {
if (!_.isFunction(done)) {
throw new TypeError('fourth argument must be function');
};
asyncRecurse(rootObj, iteratee, options, done);
return null;
}
return asyncRecursePromised(rootObj, iteratee, options)
};
function asyncRecurse(rootObj, iteratee, options, done) {
queue = async.queue(iteratee, options.parallel ? Infinity : 1);
queue.drain = () => done(null);
if (_.isObject(rootObj) && _.isEmpty(rootObj) && !options.include) {
return done(null);
}
doRecurse(rootObj, iteratee, options, queue, done);
// immediately after synchronous traverse
if (!queue.started) { // nothing added
return done(null); // prevent hang
}
};
// Returns a promise. Also, iteratee can be a promise
function asyncRecursePromised(rootObj, iteratee, options) {
// if iteratee is a Promise then convert to a traditional callback function
const callbackedIteratee = iteratee instanceof Promise ? (val, callback) => {
iteratee
.then(() => callback(null))
.catch(callback);
} : iteratee;
return new Promise((resolve, reject) => {
return asyncRecurse(rootObj, callbackedIteratee, options, (err) => {
return err ? reject(err) : resolve(null);
});
});
};
// NOTE: done is only passed so that it can be called prematurely in error case. In success case it
// does not get called in the doRecurse helper
function doRecurse(rootObj, iteratee, options, queue, done) {
if (!_.isObject(rootObj)) {
if (options.includeLeaves) {
queue.push(rootObj, (err) => {
if (err) {
queue.kill();
return done(err);
}
});
}
} else {
if (options.includeBranches) {
queue.push(rootObj, (err) => {
if (err) {
queue.kill();
return done(err);
}
});
}
_.each(rootObj, (child, i) => {
return doRecurse(child, iteratee, options, queue, done);
});
}
};
if (typeof module === 'object' && module.exports) {
module.exports = handleInput;
}