트리 데이터 구조에 대한 순진한 반복기를 구현하려고합니다. 트리의 마지막 노드 이름 ( '레벨 2 : B')이 콘솔에 인쇄되지 않는 이유는 무엇입니까? 반복자에 어떤 문제가 있습니까?
class Node {
constructor(name) {
this.name = name;
this.child = [];
}
add(name) {
const node = new Node(name);
this.child.push(node);
return node;
}
[Symbol.iterator]() {
return this;
}
next() {
if (this.current === undefined) {
this.current = 0;
return {
done: (this.child.length > 0) ? false : true,
value: this
}
}
const other = this.child[this.current].next();
if (other.done) {
this.current++;
if (this.current < this.child.length) {
other.done = false;
}
}
return other;
}
}
const root = new Node('level 0');
let node = root.add('level 1: A');
node.add('level 2: A');
root.add('level 1: B');
root.add('level 1: C');
node = root.add('level 1: D');
node.add('level 2: B');
for (const node of root) {
console.log(node.name);
}
console.log(root);
이것은 매우 간단해야하지만 작동하지 않습니다.
마지막 노드에는 자식이 없기 때문에 다음을 반환합니다.
return {
done: true,
value: this
}
done 이로 설정 되었기 때문에 true
이것은 반복자 의 산출 된 값이 아니라 반환 값입니다. 수동으로 호출하면 얻을 수 .next()
있지만 for..of
무시합니다.
이 솔루션은하는 것입니다 양보 this
첫 번째 (세트 done
에를 false
) 다음 반환 .
그러나 실제로 Node
는 반복자가 아니라 반복 가능해야합니다. 그러면 쉽게 구현할 수 있습니다.
[Symbol.iterator]*() {
yield this;
for(const child of this.child)
yield* child;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다