From 218a9c36438ab86ba8f69798f7bf8cc36e6ff327 Mon Sep 17 00:00:00 2001 From: Aonghus O Nia Date: Fri, 6 Mar 2020 22:30:12 -0500 Subject: [PATCH 1/2] Make the linked list an iterable --- src/data-structures/linked-list/LinkedList.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/data-structures/linked-list/LinkedList.js b/src/data-structures/linked-list/LinkedList.js index e256b1fe..b2cf94f2 100644 --- a/src/data-structures/linked-list/LinkedList.js +++ b/src/data-structures/linked-list/LinkedList.js @@ -235,4 +235,21 @@ export default class LinkedList { return this; } + + /** + * make the linked list iterable + * @return {iterator} + */ + [Symbol.iterator]() { + let currentNode = this.head; + + return { + next: () => { + if (!currentNode) return { done: true }; + const { value, next } = currentNode; + currentNode = next; + return { value, done: false }; + }, + }; + } } From c387aab2e778213deb630194efa95a0a0babf63c Mon Sep 17 00:00:00 2001 From: Aonghus O Nia Date: Fri, 6 Mar 2020 22:37:06 -0500 Subject: [PATCH 2/2] tests linked list is iterable --- .../linked-list/__test__/LinkedList.test.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/data-structures/linked-list/__test__/LinkedList.test.js b/src/data-structures/linked-list/__test__/LinkedList.test.js index 3a4241c9..2706654d 100644 --- a/src/data-structures/linked-list/__test__/LinkedList.test.js +++ b/src/data-structures/linked-list/__test__/LinkedList.test.js @@ -243,4 +243,17 @@ describe('LinkedList', () => { expect(linkedList.head.value).toBe(1); expect(linkedList.tail.value).toBe(3); }); + + it('should be iterable', () => { + const linkedList = new LinkedList(); + expect(typeof linkedList[Symbol.iterator]).toBe('function'); + + // Add test values to linked list. + linkedList + .append(1) + .append(2) + .append(3); + + expect([...linkedList]).toEqual([1, 2, 3]); + }); });