diff --git a/src/data-structures/linked-list/LinkedList.js b/src/data-structures/linked-list/LinkedList.js index ba7d0e3e..73aa3afa 100644 --- a/src/data-structures/linked-list/LinkedList.js +++ b/src/data-structures/linked-list/LinkedList.js @@ -269,4 +269,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 }; + }, + }; + } } diff --git a/src/data-structures/linked-list/__test__/LinkedList.test.js b/src/data-structures/linked-list/__test__/LinkedList.test.js index 6ac41ddf..cb0d58d0 100644 --- a/src/data-structures/linked-list/__test__/LinkedList.test.js +++ b/src/data-structures/linked-list/__test__/LinkedList.test.js @@ -279,4 +279,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]); + }); });