From 218a9c36438ab86ba8f69798f7bf8cc36e6ff327 Mon Sep 17 00:00:00 2001 From: Aonghus O Nia Date: Fri, 6 Mar 2020 22:30:12 -0500 Subject: [PATCH] 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 }; + }, + }; + } }