parra: parallel computations made easy
To install:
npm i parra
Note: This library is still in a very experimental stage of development. Feel free to report any issues here.
This library wraps run-with-worker with Array functions that enable easy, safe, and platform-agnostic parallel computations in JavaScript Web Workers.
It currently supports:
- a parallel
Array.mapequivalent - a parallel
Array.reduceequivalent
As with the core run-with-worker package, the amount of overhead Web Workers introduce makes parallelization only useful for computations that would take more than a few milliseconds.
Examples
test("parallelMap: powers of 2", async () => { const res = await parallelMap( // number of threads (Workers) to split work between 4, // items to process [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], // computation to perform on each item (item, [base]) => base ** item, // any extra dependencies to send to the workers [2], ); expect(res).toEqual([2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]); }); test("parallelReduce: sum of numbers", async () => { const res = await parallelReduce( 4, Array.from({ length: 100 }).map((_, i) => i + 1), (acc, item) => acc + item, 0, [], ); expect(res).toEqual(5050); }); test("parallelReduce: product of numbers", async () => { const res = await parallelReduce( 4, Array.from({ length: 10 }).map((_, i) => i + 1), (acc, item) => acc * item, 1, [], ); expect(res).toEqual(3628800); });