WPC Class Generator Example

This example demonstrates π approximation with BigInt in a separate browser thread using a WPC Class. The result is sent back to the main thread every 1000 iterations.

π = 3.14
HelloWorkerYield.ts
WorkerYieldExample.tsx
1import { worker } from 'vovk';
2
3@worker()
4export default class HelloWorkerYield {
5 /**
6 * Calculate Pi using a series expansion with BigInt for high precision
7 * @param scalePower - power of 10 to scale the calculations for precision
8 * @param yieldEvery - how often to yield the result
9 */
10 static *approximatePi(scalePower: bigint, yieldEvery: number) {
11 let i = 1n;
12 let x = 3n * 10n ** scalePower;
13 let pi = x;
14 let count = 0;
15 while (x > 0) {
16 x = (x * i) / ((i + 1n) * 4n);
17 pi += x / (i + 2n);
18 i += 2n;
19 if (count++ % yieldEvery === 0) {
20 yield pi;
21 }
22 }
23 }
24}
1import { worker } from 'vovk';
2
3@worker()
4export default class HelloWorkerYield {
5 /**
6 * Calculate Pi using a series expansion with BigInt for high precision
7 * @param scalePower - power of 10 to scale the calculations for precision
8 * @param yieldEvery - how often to yield the result
9 */
10 static *approximatePi(scalePower: bigint, yieldEvery: number) {
11 let i = 1n;
12 let x = 3n * 10n ** scalePower;
13 let pi = x;
14 let count = 0;
15 while (x > 0) {
16 x = (x * i) / ((i + 1n) * 4n);
17 pi += x / (i + 2n);
18 i += 2n;
19 if (count++ % yieldEvery === 0) {
20 yield pi;
21 }
22 }
23 }
24}