mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-09-20 07:43:04 +08:00
Merge 52d42cf70c
into ca3d16dcce
This commit is contained in:
commit
2f4bb188bc
@ -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 };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -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]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
Loading…
Reference in New Issue
Block a user