Compare commits

...

4 Commits

Author SHA1 Message Date
Aonghus O Nia
9dc2ef3f63
Merge 52d42cf70c into 2c67b48c21 2024-04-25 08:20:34 +08:00
Aonghus O Nia
52d42cf70c
Merge branch 'master' into master 2020-09-02 22:22:21 -04:00
Aonghus O Nia
c387aab2e7
tests linked list is iterable 2020-03-06 22:37:06 -05:00
Aonghus O Nia
218a9c3643
Make the linked list an iterable 2020-03-06 22:30:12 -05:00
2 changed files with 30 additions and 0 deletions

View File

@ -269,4 +269,21 @@ export default class LinkedList {
return this; 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.head.value).toBe(1);
expect(linkedList.tail.value).toBe(3); 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]);
});
}); });