perf: alternate worker selection between start and end of worker nodes
[poolifier.git] / src / pools / selection-strategies / abstract-worker-choice-strategy.ts
index 2f1905782f7c4a6c3d6d4c98053b3965eaa8021d..bddb8b76566fd62545e1552618712dc39d98e7b9 100644 (file)
@@ -19,6 +19,10 @@ export abstract class AbstractWorkerChoiceStrategy<
   Data = unknown,
   Response = unknown
 > implements IWorkerChoiceStrategy {
+  /**
+   * Toggles finding the last free worker node key.
+   */
+  private toggleFindLastFreeWorkerNodeKey: boolean = false
   /** @inheritDoc */
   protected readonly isDynamicPool: boolean
   /** @inheritDoc */
@@ -68,4 +72,18 @@ export abstract class AbstractWorkerChoiceStrategy<
     this.checkOptions(opts)
     this.opts = opts
   }
+
+  /**
+   * Finds a free worker node key.
+   *
+   * @returns The free worker node key or `-1` if there is no free worker node.
+   */
+  protected findFreeWorkerNodeKey (): number {
+    if (this.toggleFindLastFreeWorkerNodeKey) {
+      this.toggleFindLastFreeWorkerNodeKey = false
+      return this.pool.findLastFreeWorkerNodeKey()
+    }
+    this.toggleFindLastFreeWorkerNodeKey = true
+    return this.pool.findFreeWorkerNodeKey()
+  }
 }