Skip to content

Instantly share code, notes, and snippets.

@lupomontero
Created June 20, 2018 03:48
Show Gist options
  • Save lupomontero/e9c8b725368535e4f70e229b4077b7eb to your computer and use it in GitHub Desktop.
Save lupomontero/e9c8b725368535e4f70e229b4077b7eb to your computer and use it in GitHub Desktop.
const splitArrayIntoBatches = (arr, limit) => arr.reduce((memo, item) => {
if (memo.length && memo[memo.length - 1].length < limit) {
memo[memo.length - 1].push(item);
return memo;
}
return [...memo, [item]];
}, []);
const pact = (tasks, concurrency, interval = 0, failFast = true) => {
const processBatches = (batches, prevResults = []) => {
if (!batches.length) {
return Promise.resolve(prevResults);
}
return Promise.all(
batches[0].map(fn => (failFast ? fn() : fn().catch(err => err))),
).then((batchResults) => {
const results = [...prevResults, ...batchResults];
return (batches.length <= 1)
? results
: new Promise((resolve, reject) => setTimeout(
() => processBatches(batches.slice(1), results).then(resolve, reject),
interval,
));
});
};
return processBatches(splitArrayIntoBatches(tasks, concurrency));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment