perf(simulator): filter array for undefined before running map()
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
2
3 import { parentPort, workerData } from 'worker_threads';
4
5 import { ThreadWorker } from 'poolifier';
6
7 import { ChargingStation } from './ChargingStation';
8 import { ChargingStationUtils } from './ChargingStationUtils';
9 import type { ChargingStationWorkerData } from '../types';
10 import { Utils } from '../utils/Utils';
11 import { WorkerConstants, type WorkerMessage, WorkerMessageEvents } from '../worker';
12
13 // Conditionally export ThreadWorker instance for pool usage
14 export let threadWorker: ThreadWorker;
15 if (ChargingStationUtils.workerPoolInUse()) {
16 threadWorker = new ThreadWorker<ChargingStationWorkerData>(startChargingStation, {
17 maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME,
18 async: false,
19 });
20 } else {
21 // Add message listener to start charging station from main thread
22 addMessageListener();
23 if (Utils.isUndefined(workerData) === false) {
24 startChargingStation(workerData as ChargingStationWorkerData);
25 }
26 }
27
28 /**
29 * Listen messages send by the main thread
30 */
31 function addMessageListener(): void {
32 parentPort?.on('message', (message: WorkerMessage<ChargingStationWorkerData>) => {
33 if (message.id === WorkerMessageEvents.START_WORKER_ELEMENT) {
34 startChargingStation(message.data);
35 }
36 });
37 }
38
39 /**
40 * Create and start a charging station instance
41 *
42 * @param data - workerData
43 */
44 function startChargingStation(data: ChargingStationWorkerData): void {
45 const station = new ChargingStation(data.index, data.templateFile);
46 station.start();
47 }