I'm implementing a doubly linked list as part of a programming exercise, and I would like to allow the developer to iterate through its nodes both forward and backwards using the for...in notation.
At its most basic, the data structure looks like this:
class DoublyLinkedList {
constructor(data) {
if (data) {
this.head = new DoublyLinkedListNode(data)
} else {
this.head = null
}
}
append = (data) => {
if (!this.head) {
this.prepend(data)
} else {
const newTail = new DoublyLinkedListNode(data)
let current = this.head
while(current.next) {
current = current.next
}
current.next = newTail
newTail.prev = current
}
}
}
Next I added the generator functions:
*values() {
let current = this.head
while (current) {
yield current.data;
current = current.next;
}
}
*valuesBackward() {
let currentForwards = this.head
while (currentForwards.next) {
currentForwards = currentForwards.next
}
const tail = currentForwards
let currentBackwards = tail
while (currentBackwards) {
yield currentBackwards.data
currentBackwards = currentBackwards.prev
}
}
I'm able to add a single, forwards iterator with the following added to the class:
[Symbol.iterator]() { return this.values()}
I tried adding both of the following to the class:
iterateForward = () => [Symbol.iterator] = () => this.valuesBackward()
iterateBackward = () => [Symbol.iterator] = () => this.valuesBackward()
And then tried to iterate using for (node in list.iterateForward()) but this failed with error TypeError: undefined is not a function.
I guess that made sense looking at the code so next I tried:
iterateForward = () => {
const vals = this.values()
const it = {
[Symbol.iterator]() {
return vals()
}
}
return it
}
This didn't error, but the iteration didn't work - the iterator ran zero times.
What am I missing here? Is it possible to achieve what I want?