npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

parallel-function

v1.0.6

Published

Multithreading. Perform async calls to an automatically 'worker-wrapped' function

Downloads

24

Readme

ParallelFunction

Create a new thread with your function, and keep it ready to be called as many times as you need, asynchronously in the background, without blocking your main thread event loop.

Features

  • [x] Generate/Destroy threaded functions on demmand.
  • [x] Execute your functions as a regular async function call.
  • [x] Unlease the power of multithreading keeping your code clean.
  • [x] Compatible with Promise.race() & Promise.all()
  • [x] Availability to use Transfereable Objects and sharedArrayBuffers.
  • [x] Browser support : Firefox 59, Edge 41, Chrome 65
  • [ ] Node support... ¿Soon?

Syntax

let myParallelFunction = new ParallelFunction( myFunction );

  • myFunction function,required : Function to be injected in the worker. If it has no name defined, it will be declared inside the worker as self._parallelFunction, otherwise the name will be respected. Async functions are accepted. Read the section Details to find out the allowed types to be returned.

Usage

The ParallelFunction Constructor returns an interface-function, wich handles the async calls to your function.

async myParallelFunction( ...args ); // ...will execute your function

Your reference to the created ParallelFunction, contains some usefull methods, like a method to Destroy the thread, when is not anymore required.

myParallelFunction.destroy();

As well provides some methods to perform advanced implementations, combining the simple interface of the library and the native Worker API. This methods, expose the worker API. For more infomation about them, check the Mozilla documentation

myParallelFunction.postMessage( message, transferList );

myParallelFunction.onMessage( handlerFunction );

Example

A minimal example, to interact with a ParallelFunction :

    // Generate a ParallelFunction to calculate Pi,
    // with customizable precision. The bigger
    // is n, the  longuer is going to take
    let calculatePi = new ParallelFunction( function(n){
        var v = 0;
        for(let i=1; i<=n; i+=4) v += ( 1/i ) - ( 1/(i+2) );
        return 4*v;
    });
    
    // perform the calculation, with different precisions
    calculatePi(1000000).then( r=> console.log(r) );
    calculatePi(1000000000).then( r=> console.log(r) );

    // use the Promise await keyword inside async functions
    (async function(){
        let pi = await calculatePi(1000000000);
	    console.log( pi );
        // done! destroy the reference
        calculatePi.destroy();
    })()

Installation

Use any of the following distribution channels:

  • Embeed from a Global CDN
<script src="https://cdn.rawgit.com/colxi/parallel-function/a8abdc44/parallel-function.min.js"></script>
  • Use npm
$ npm -i parallel-function
  • Clone from github
https://github.com/colxi/parallel-function

Details

  • Because each request needs to be messaged to the worker, and its result, messaged back, all interactions with the function are ASYNCHRONOUS.

  • Your Parallel Function doesn't run in the same scope where was declared , but in an isolate scope inside a worker, this means, it cannot reach any variable declared in the main thread. However has acces to all the methods of the Web Worker API

  • Only those values wich can be handled by the Structure Clone Algorithm are candidates to be passed/retrieved through the function calls.

All primitive types, Except symbols -- Boolean object -- String object -- Date -- RegExp, The lastIndex field is not preserved -- Blob -- File -- FileList -- ArrayBuffer -- ArrayBufferView, All typed arrays (like Int32Array etc.) -- ImageData -- Array -- Object, Just plain objects (e.g. from object literals) -- Map -- Set

  • Because the worker allows natively powerfull interactions throught the standard Messages, this library lets you use them, in order to unlease the real power of workers (and make use of trafereable objects, sharedArrayBuffers...)

Node support

Until Workers API isn't available in Node, this library is exclusive for Browsers. Threads to track:

Worker support https://github.com/nodejs/node/issues/13143

Implement createObjectURL/Blob from File API https://github.com/nodejs/node/issues/16167

Implementation overview

The mechanism is pretty simple and straight forward.

ParallelFunction = Blobs + Workers + Promises

The library injects into a new Worker, a Blob containing the code of the communication layer, and the provided function, and handles each function call adding it to the messages queue, using a unique index ID. When a call is returned, it resolves the Promise associated with the call ID.