Last active
June 30, 2022 11:23
-
-
Save churchofthought/b1a937929de44afb322ab850b4a3f169 to your computer and use it in GitHub Desktop.
This file contains 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
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