This commit is contained in:
Aonghus O Nia 2024-07-17 10:38:56 +09:00 committed by GitHub
commit 2f4bb188bc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 30 additions and 0 deletions

View File

@ -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 };
},
};
}
}

View File

@ -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]);
});
});