perf: remove unneeded class indirection for dynamic pool in worker
[poolifier.git] / src / pools / selection-strategies / weighted-round-robin-worker-choice-strategy.ts
index e3d2be3f3e1c20d158d70dc0e85943e59bfeac4c..3709cce409b4ba988a728f81f0f8c6eb65f205f8 100644 (file)
@@ -2,7 +2,10 @@ import { cpus } from 'node:os'
 import type { IPoolInternal } from '../pool-internal'
 import type { IPoolWorker } from '../pool-worker'
 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
-import type { RequiredStatistics } from './selection-strategies-types'
+import type {
+  IWorkerChoiceStrategy,
+  RequiredStatistics
+} from './selection-strategies-types'
 
 /**
  * Virtual task runtime.
@@ -21,13 +24,16 @@ interface TaskRunTime {
  * @typeParam Response - Type of response of execution. This can only be serializable data.
  */
 export class WeightedRoundRobinWorkerChoiceStrategy<
-  Worker extends IPoolWorker,
-  Data,
-  Response
-> extends AbstractWorkerChoiceStrategy<Worker, Data, Response> {
+    Worker extends IPoolWorker,
+    Data,
+    Response
+  >
+  extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
+  implements IWorkerChoiceStrategy {
   /** {@inheritDoc} */
   public readonly requiredStatistics: RequiredStatistics = {
-    runTime: true
+    runTime: true,
+    avgRunTime: true
   }
 
   /**
@@ -93,6 +99,23 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
     return chosenWorkerKey
   }
 
+  /** {@inheritDoc} */
+  public remove (workerKey: number): boolean {
+    if (this.currentWorkerId === workerKey) {
+      this.currentWorkerId =
+        this.currentWorkerId > this.pool.workers.length - 1
+          ? this.pool.workers.length - 1
+          : this.currentWorkerId
+    }
+    const workerDeleted = this.workersTaskRunTime.delete(workerKey)
+    for (const [key, value] of this.workersTaskRunTime) {
+      if (key > workerKey) {
+        this.workersTaskRunTime.set(key - 1, value)
+      }
+    }
+    return workerDeleted
+  }
+
   private initWorkersTaskRunTime (): void {
     for (const [index] of this.pool.workers.entries()) {
       this.initWorkerTaskRunTime(index)