refactor: untangle worker choosing code from worker creation code
[poolifier.git] / src / pools / selection-strategies / weighted-round-robin-worker-choice-strategy.ts
index a8848f14ee80570f7c2d9e294d9d3552cfec3757..ea598b207f2e1b20358ce0cd6c5da134077ae8f1 100644 (file)
@@ -25,12 +25,12 @@ interface TaskRunTime {
  */
 export class WeightedRoundRobinWorkerChoiceStrategy<
     Worker extends IPoolWorker,
-    Data,
-    Response
+    Data = unknown,
+    Response = unknown
   >
   extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
-  implements IWorkerChoiceStrategy<Worker, Data, Response> {
-  /** {@inheritDoc} */
+  implements IWorkerChoiceStrategy {
+  /** @inheritDoc */
   public readonly requiredStatistics: RequiredStatistics = {
     runTime: true,
     avgRunTime: true
@@ -63,7 +63,7 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
     this.initWorkersTaskRunTime()
   }
 
-  /** {@inheritDoc} */
+  /** @inheritDoc */
   public reset (): boolean {
     this.currentWorkerId = 0
     this.workersTaskRunTime.clear()
@@ -71,7 +71,7 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
     return true
   }
 
-  /** {@inheritDoc} */
+  /** @inheritDoc */
   public choose (): number {
     const chosenWorkerKey = this.currentWorkerId
     if (this.isDynamicPool && !this.workersTaskRunTime.has(chosenWorkerKey)) {
@@ -99,13 +99,17 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
     return chosenWorkerKey
   }
 
-  /** {@inheritDoc} */
+  /** @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
+      if (this.pool.workers.length === 0) {
+        this.currentWorkerId = 0
+      } else {
+        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) {