Skip to content

Commit

Permalink
feat: extract worker function
Browse files Browse the repository at this point in the history
  • Loading branch information
andreashuber69 committed Apr 21, 2024
1 parent 56067d9 commit f657619
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
17 changes: 8 additions & 9 deletions src/FibonacciWorker.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import { implementWorker } from "kiss-worker";
import { implementWorkerExternal } from "kiss-worker";

// The function we want to execute on a worker thread (worker function).
const getFibonacci = (n: number): number =>
((n < 2) ? Math.floor(n) : getFibonacci(n - 1) + getFibonacci(n - 2));
// Import the type of the worker function ...
import type { GetFibonacci } from "./getFibonacci.js";

export const FibonacciWorker = implementWorker(
// A function that creates a web worker running this script
// ... and pass it to establish type safety
export const FibonacciWorker = implementWorkerExternal<GetFibonacci>(
// A function that creates a web worker running the script that serves
// the worker function
() => new Worker(
new URL("FibonacciWorker.js", import.meta.url),
new URL("getFibonacci.js", import.meta.url),
{ type: "module" }
),
// Our worker function
getFibonacci,
);
11 changes: 11 additions & 0 deletions src/getFibonacci.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { serve } from "kiss-worker";

// The function we want to execute on a worker thread (worker function)
const getFibonacci = (n: number): number =>
((n < 2) ? Math.floor(n) : getFibonacci(n - 1) + getFibonacci(n - 2));

// Serve the function, so that it can be called from another thread
serve(getFibonacci);

// Export the type only
export type GetFibonacci = typeof getFibonacci;

0 comments on commit f657619

Please sign in to comment.