Created
August 13, 2020 09:58
-
-
Save lionelB/4b295e50e6d449221080e81b6ce393c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function range(start, end, size = 1) { | |
return Array.from( | |
{ length: Math.ceil((end - start) / size) }, | |
(_, i) => start + i * size | |
); | |
} | |
function batch(items, size) { | |
return range(0, items.length, size).map(val => { | |
return items.slice(val, val + size); | |
}); | |
} | |
export async function batchPromise(list, size, callback) { | |
let results = []; | |
let nbBatch = 0; | |
for (const items of batch(list, size)) { | |
const values = await Promise.all( | |
items.map((item, i) => callback(item, i + nbBatch * size, list)) | |
); | |
nbBatch += 1; | |
results = [...results, ...values]; | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment