How it works...

Shared array buffers can be shared across any number of worker threads. In order to calculate portions of the result, we need to divide the results equitably between the threads. That's what the 'load-indices' case of the worker onMessage listener does.

We can use the size of the array and the total worker count to get the window size. We take the floor so that we don't go beyond the index of the array. This is also because you can't have a partial index: they are integers.

Next, we use the current worker index to get the startIndex (basically picking up where the previous worker left off). To get the end index, we need to know if this is the last worker. If not, we use the window size. If it is, we need to take all of the ...

Get ECMAScript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.