WorkerFactory.ts: Use nullish coalescing operator
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerFactory.ts
1 import { WorkerOptions, WorkerProcessType } from '../types/Worker';
2
3 import Utils from '../utils/Utils';
4 import WorkerAbstract from './WorkerAbstract';
5 import WorkerDynamicPool from './WorkerDynamicPool';
6 import WorkerSet from './WorkerSet';
7 import WorkerStaticPool from './WorkerStaticPool';
8 import { isMainThread } from 'worker_threads';
9
10 export default class WorkerFactory {
11 public static getWorkerImplementation<T>(workerScript: string, workerProcessType: WorkerProcessType, options?: WorkerOptions): WorkerAbstract {
12 if (!isMainThread) {
13 throw new Error('Trying to get a worker implementation outside the main thread');
14 }
15 if (Utils.isUndefined(options)) {
16 options = {} as WorkerOptions;
17 }
18 switch (workerProcessType) {
19 case WorkerProcessType.WORKER_SET:
20 options.elementsPerWorker = options.elementsPerWorker ?? 1;
21 return new WorkerSet<T>(workerScript, options.elementsPerWorker);
22 case WorkerProcessType.STATIC_POOL:
23 options.poolMaxSize = options.poolMaxSize ?? 16;
24 return new WorkerStaticPool<T>(workerScript, options.poolMaxSize);
25 case WorkerProcessType.DYNAMIC_POOL:
26 options.poolMinSize = options.poolMinSize ?? 4;
27 options.poolMaxSize = options.poolMaxSize ?? 16;
28 return new WorkerDynamicPool<T>(workerScript, options.poolMinSize, options.poolMaxSize);
29 default:
30 return null;
31 }
32 }
33 }