refactor: align findFreeWorkerKey() return type with findIndex()
[poolifier.git] / src / pools / selection-strategies / round-robin-worker-choice-strategy.ts
index a23275873909b0731cb3d514af74f0b9fb59090a..1499db945f8297181724db968f21b938d8f3618b 100644 (file)
@@ -1,5 +1,6 @@
 import type { IPoolWorker } from '../pool-worker'
 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
+import type { IWorkerChoiceStrategy } from './selection-strategies-types'
 
 /**
  * Selects the next worker in a round robin fashion.
@@ -9,10 +10,12 @@ import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
  * @typeParam Response - Type of response of execution. This can only be serializable data.
  */
 export class RoundRobinWorkerChoiceStrategy<
-  Worker extends IPoolWorker,
-  Data,
-  Response
-> extends AbstractWorkerChoiceStrategy<Worker, Data, Response> {
+    Worker extends IPoolWorker,
+    Data,
+    Response
+  >
+  extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
+  implements IWorkerChoiceStrategy {
   /**
    * Id of the next worker.
    */
@@ -25,12 +28,23 @@ export class RoundRobinWorkerChoiceStrategy<
   }
 
   /** {@inheritDoc} */
-  public choose (): Worker {
-    const chosenWorker = this.pool.workers[this.nextWorkerId]?.worker
+  public choose (): number {
+    const chosenWorkerKey = this.nextWorkerId
     this.nextWorkerId =
       this.nextWorkerId === this.pool.workers.length - 1
         ? 0
         : this.nextWorkerId + 1
-    return chosenWorker
+    return chosenWorkerKey
+  }
+
+  /** {@inheritDoc} */
+  public remove (workerKey: number): boolean {
+    if (this.nextWorkerId === workerKey) {
+      this.nextWorkerId =
+        this.nextWorkerId > this.pool.workers.length - 1
+          ? this.pool.workers.length - 1
+          : this.nextWorkerId
+    }
+    return true
   }
 }