From 68799d7e70a1597f21b1ea7e415686fd72422b18 Mon Sep 17 00:00:00 2001 From: slikts Date: Tue, 24 Jan 2023 13:34:24 +0000 Subject: [PATCH] feat(LinkedQueue): implement iteration protocols --- src/LinkedQueue.spec.ts | 7 +++++++ src/LinkedQueue.ts | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/LinkedQueue.spec.ts b/src/LinkedQueue.spec.ts index 48e686d0..d60c9457 100644 --- a/src/LinkedQueue.spec.ts +++ b/src/LinkedQueue.spec.ts @@ -64,4 +64,11 @@ describe('LinkedQueue', () => { q.forEach(() => void (n += 1)); expect(n).toBe(2); }); + + it('iterates', () => { + const q = new LinkedQueue(); + q.enqueue(1); + q.enqueue(2); + expect([...q]).toEqual([1, 2]); + }); }); diff --git a/src/LinkedQueue.ts b/src/LinkedQueue.ts index 676a3edc..558057aa 100644 --- a/src/LinkedQueue.ts +++ b/src/LinkedQueue.ts @@ -47,4 +47,22 @@ export default class LinkedQueue { forEach(f: (value: A) => void): void { this.#list.forEach(f); } + + [Symbol.iterator]() { + return { + next: () => { + return this.length > 0 + ? { + value: this.dequeue(), + done: false, + } + : { + done: true, + }; + }, + [Symbol.iterator]() { + return this; + }, + }; + } }