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