Skip to content

Instantly share code, notes, and snippets.

@churchofthought
Last active June 30, 2022 11:23
Show Gist options
  • Save churchofthought/b1a937929de44afb322ab850b4a3f169 to your computer and use it in GitHub Desktop.
Save churchofthought/b1a937929de44afb322ab850b4a3f169 to your computer and use it in GitHub Desktop.
const parallelMap = async (arr, f, n = Infinity, inPlace = false) => {
const results = inPlace ? arr : Array(arr.length)
const entries = arr.entries()
const worker = async () => {
for (const [key, val] of entries)
results[key] = await f(val, key)
}
await Promise.all(
Array.from({length: Math.min(arr.length, n)}, worker)
)
return results
}
const parallelDo = async (arr, f, n = Infinity) => {
const entries = arr.entries()
const worker = async () => {
for (const [key, val] of entries)
await f(val, key)
}
await Promise.all(
Array.from({length: Math.min(arr.length, n)}, worker)
)
}
const delay = t => new Promise(r => setTimeout(r, t, t))
// test parallelMap
for (var n = 1; n <= 5; ++n) {
const tid = `${n} workers`
console.time(tid); console.log(await parallelMap(await [100, 200, 400, 800, 1600],delay, n)); console.timeEnd(tid)
}
// test parallelDo
for (var n = 1; n <= 5; ++n) {
const tid = `${n} workers`
console.time(tid); console.log(await parallelDo(await [100, 200, 400, 800, 1600],delay, n)); console.timeEnd(tid)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment