2018-12-22 21:05:13 +00:00
|
|
|
export const sequence = function sequence(tasks, fn) {
|
|
|
|
return tasks.reduce(
|
|
|
|
(promise, task) => promise.then(() => fn(task)),
|
|
|
|
Promise.resolve()
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
export const parallel = function parallel(tasks, fn) {
|
|
|
|
return Promise.all(tasks.map(fn))
|
|
|
|
}
|
|
|
|
|
|
|
|
export const chainFn = function chainFn(base, fn) {
|
|
|
|
if (typeof fn !== 'function') {
|
|
|
|
return base
|
|
|
|
}
|
2019-01-17 21:18:29 +00:00
|
|
|
return function (...args) {
|
2018-12-22 21:05:13 +00:00
|
|
|
if (typeof base !== 'function') {
|
2019-01-17 21:18:29 +00:00
|
|
|
return fn.apply(this, args)
|
2018-12-22 21:05:13 +00:00
|
|
|
}
|
2019-01-17 21:18:29 +00:00
|
|
|
let baseResult = base.apply(this, args)
|
2018-12-22 21:05:13 +00:00
|
|
|
// Allow function to mutate the first argument instead of returning the result
|
|
|
|
if (baseResult === undefined) {
|
2019-01-17 21:18:29 +00:00
|
|
|
[baseResult] = args
|
2018-12-22 21:05:13 +00:00
|
|
|
}
|
|
|
|
const fnResult = fn.call(
|
|
|
|
this,
|
|
|
|
baseResult,
|
2019-01-17 21:18:29 +00:00
|
|
|
...Array.prototype.slice.call(args, 1)
|
2018-12-22 21:05:13 +00:00
|
|
|
)
|
|
|
|
// Return mutated argument if no result was returned
|
|
|
|
if (fnResult === undefined) {
|
|
|
|
return baseResult
|
|
|
|
}
|
|
|
|
return fnResult
|
|
|
|
}
|
|
|
|
}
|