Offload functions to worker threads with shared memory primitives for Node.js.
1import { describe, it } from 'node:test';
2import assert from 'node:assert/strict';
3import { inert, isTask, workers } from 'moroutine';
4import type { Task } from 'moroutine';
5import { checkPrime, upper, countUp } from './fixtures/is-task.ts';
6
7describe('isTask', () => {
8 it('exposes a stable id on the moroutine', () => {
9 assert.equal(typeof checkPrime.id, 'string');
10 assert.ok(checkPrime.id.length > 0);
11 assert.notEqual(checkPrime.id, upper.id);
12 });
13
14 it('identifies tasks produced by a moroutine', () => {
15 const t = inert(checkPrime(7));
16 assert.ok(isTask(checkPrime, t));
17 assert.ok(!isTask(upper, t));
18 });
19
20 it('works across value and streaming moroutines', () => {
21 const v = inert(checkPrime(7));
22 const s = inert(countUp(3));
23 assert.ok(isTask(checkPrime, v));
24 assert.ok(!isTask(countUp, v));
25 assert.ok(isTask(countUp, s));
26 assert.ok(!isTask(checkPrime, s));
27 });
28
29 it('narrows task args for downstream dispatch', async () => {
30 using run = workers(1);
31 const tasks: Array<Task<boolean, [n: number]> | Task<string, [s: string]>> = [
32 inert(checkPrime(5)),
33 inert(upper('hi')),
34 ];
35 const results: Array<boolean | string> = [];
36 for (const t of tasks) {
37 if (isTask(checkPrime, t)) {
38 // t is Task<boolean, [n: number]> — args typed as [n: number]
39 const [n] = t.args;
40 assert.equal(typeof n, 'number');
41 results.push(await run(t));
42 } else {
43 const [s] = t.args;
44 assert.equal(typeof s, 'string');
45 results.push(await run(t));
46 }
47 }
48 assert.deepEqual(results, [true, 'HI']);
49 });
50});