feat: add backward iterator to deque
authorJérôme Benoit <jerome.benoit@piment-noir.org>
Wed, 23 Aug 2023 12:17:34 +0000 (14:17 +0200)
committerJérôme Benoit <jerome.benoit@piment-noir.org>
Wed, 23 Aug 2023 12:17:34 +0000 (14:17 +0200)
Signed-off-by: Jérôme Benoit <jerome.benoit@piment-noir.org>
src/deque.ts
src/pools/selection-strategies/abstract-worker-choice-strategy.ts
tests/deque.test.js

index 109304a83e2de9ac4470b121817fde9f0803f630..49373cef998ec1afc7f27b63a678e1d3914796b4 100644 (file)
@@ -154,6 +154,30 @@ export class Deque<T> {
     }
   }
 
+  backward (): Iterable<T> {
+    return {
+      [Symbol.iterator]: (): Iterator<T> => {
+        let node = this.tail
+        return {
+          next: () => {
+            if (node == null) {
+              return {
+                value: undefined,
+                done: true
+              }
+            }
+            const ret = {
+              value: node.value,
+              done: false
+            }
+            node = node.prev as Node<T>
+            return ret
+          }
+        }
+      }
+    }
+  }
+
   private incrementSize (): number {
     ++this.size
     if (this.size > this.maxSize) {
index c2b4d1d3d37b56c5101c235fa2f49cfcfb6bd5fd..2fba4e9fbd1a17be10fd9d6a86a6cb574a9ad03b 100644 (file)
@@ -197,15 +197,15 @@ export abstract class AbstractWorkerChoiceStrategy<
   /**
    * Check the next worker node eligibility.
    *
-   * @param chosenWorkerNodeKey - The chosen worker node key.
+   * @param chosenNextWorkerNodeKey - The chosen worker node key.
    */
   protected checkNextWorkerNodeEligibility (
-    chosenWorkerNodeKey: number | undefined
+    chosenNextWorkerNodeKey: number | undefined
   ): void {
     if (!this.isWorkerNodeEligible(this.nextWorkerNodeKey as number)) {
       this.nextWorkerNodeKey = undefined
       this.previousWorkerNodeKey =
-        chosenWorkerNodeKey ?? this.previousWorkerNodeKey
+        chosenNextWorkerNodeKey ?? this.previousWorkerNodeKey
     }
   }
 
index dec96b3582a28605fca18d24204428e9f93da4c3..8521047d1ef7edc8aecc5eb5483c556d61b355e9 100644 (file)
@@ -123,4 +123,16 @@ describe('Deque test suite', () => {
       ++i
     }
   })
+
+  it('Verify backward() iterator behavior', () => {
+    const deque = new Deque()
+    deque.push(1)
+    deque.push(2)
+    deque.push(3)
+    let i = deque.size
+    for (const value of deque.backward()) {
+      expect(value).toBe(i)
+      --i
+    }
+  })
 })