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 };
}
function*let iterator()cursor {
= head = next;
let cursorfunction* =iterator() this.head;{
while(cursor.next) {
yield cursor;
cursor = cursor.next
}
yield cursor;
}
return {
[Symbol.iterator]: iterator,
head: next,
tail,
};
}
var ll = console.log(...link([1,2,3,4]);
console.log(...ll);
console.log(...ll);
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.
Edit:
The number one problem with the code as originally written was that cursor
was maintained at instance- rather than iterator-invocation level.
This is what "felt wrong" to me, although I could not articulate it at the time.
I have subsequently moved the position of the cursor
variable.