This is an attempt to write a function link
that creates a linked list from an array:
function link(list) {
let next = tail = null;
for(let i = list.length-1; i >= 0; i--) {
const value = list[i];
next = { value, next };
}
let cursor = head = next;
function* iterator() {
while(cursor.next) {
yield cursor;
cursor = cursor.next
}
yield cursor;
}
return {
[Symbol.iterator]: iterator,
head,
tail,
};
}
console.log(...link([1,2,3,4]));
The iterator maintains a cursor to remember its position in the iteration.
This feels wrong and brittle.
Is it?
If so, how should the iterator be implemented here.
next
property of the "previous" element. Can you explain which aspect feels wrong to you? \$\endgroup\$