@jdmichaud/ts-workers
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

ts-workers

A thin typescript layer on top of the Worker API to facilite its usage in a typesafe way. For example:

import { Task } from '../src';

async function main(): Promise<void> {
  const res: number = await Task.create((b: number) => b * 2).createThread().run(21);
  console.log(res); // 42
}

window.onload = main;

Types are checked:

  // Compilation will fail because the return type is not string but number.
  const res: string = await Task.create((b: number) => b * 2).createThread().run(21);
  // Here the parameter type is incorrect.
  const res: number = await Task.create((b: number) => b * 2).createThread().run('21');

Queue can be used to spread tasks to a pool of workers:

import { Queue, ThreadBuilder, Thread } from '../src';

async function main(): Promise<void> {
  const queue = ThreadBuilder
    .create(delay => new Promise<void>(resolve => setTimeout(() => resolve(), delay)))
    .createThreads(navigator.hardwareConcurrency)
    .queue();
  const delays = Array.from(Array(navigator.hardwareConcurrency * 2))
    .map(_ => [Math.random() * 1000 | 0]);
  const promises = queue.run(delays as any);

  promises.forEach((promise, index) => {
    const span = document.createElement('span');
    span.innerText = Number(delays[index]).toString();
    span.style.backgroundColor = '#F00';
    const div = document.createElement('div');
    div.appendChild(span);
    document.body.appendChild(div);
    promise.then(() => span.style.backgroundColor = '#0F0')
  })
}

window.onload = main;

How to use

Simply install it from the npm registry:

npm install @jdmichaud/ts-workers

Limitations

  • Works only on browsers implementing ES2020.

Contributions

Clone the project:

git clone <this repo>

Install dependencies:

npm install

Build:

npm run all

Launch the developement application:

npm run dev

License

MIT © Jean-Daniel Michaud

Readme

Keywords

Package Sidebar

Install

npm i @jdmichaud/ts-workers

Weekly Downloads

0

Version

0.1.1

License

MIT

Unpacked Size

32 kB

Total Files

11

Last publish

Collaborators

  • jdmichaud