Nuxt/packages/kit/src/utils/task.ts

43 lines
945 B
TypeScript
Raw Normal View History

export function sequence<T, R> (
2020-07-30 23:40:16 +00:00
tasks: T[],
fn: (task: T) => R
) {
2020-07-02 13:02:35 +00:00
return tasks.reduce(
2020-07-30 23:40:16 +00:00
(promise, task): any => promise.then(() => fn(task)),
2020-07-02 13:02:35 +00:00
Promise.resolve()
)
}
export function parallel<T, R> (
2020-07-30 23:40:16 +00:00
tasks: T[],
fn: (task: T) => R
) {
2020-07-02 13:02:35 +00:00
return Promise.all(tasks.map(fn))
}
export function chainFn (base, fn) {
2020-07-02 13:02:35 +00:00
if (typeof fn !== 'function') {
return base
}
return function (...args) {
if (typeof base !== 'function') {
return fn.apply(this, args)
}
let baseResult = base.apply(this, args)
// Allow function to mutate the first argument instead of returning the result
if (baseResult === undefined) {
[baseResult] = args
}
const fnResult = fn.call(
this,
baseResult,
...Array.prototype.slice.call(args, 1)
)
// Return mutated argument if no result was returned
if (fnResult === undefined) {
return baseResult
}
return fnResult
}
}