Skip to content

Commit 09d7822

Browse files
Iterate over children using an ES6 iterator
1 parent 7065691 commit 09d7822

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

lib/SymbolTree.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,36 @@ class SymbolTree {
303303
return array;
304304
}
305305

306+
childrenIterator(parent) {
307+
const _node = this._node.bind(this);
308+
309+
let nextObject = this._node(parent).first;
310+
const iterator = {};
311+
312+
iterator.next = function() {
313+
if (!nextObject) {
314+
return {
315+
done : true,
316+
value : parent
317+
};
318+
}
319+
320+
const value = nextObject;
321+
nextObject = _node(nextObject).next;
322+
323+
return {
324+
done : false,
325+
value : value
326+
};
327+
};
328+
329+
iterator[Symbol.iterator] = function() {
330+
return iterator;
331+
};
332+
333+
return iterator;
334+
}
335+
306336
/**
307337
* Remove the object from this tree.
308338
* Has no effect if already removed.

test/SymbolTree.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -673,6 +673,57 @@ test('childrenToArray with filter', function(t) {
673673
t.end();
674674
});
675675

676+
test('children iterator', function(t) {
677+
const tree = new SymbolTree();
678+
const a = {};
679+
const aa = {};
680+
const ab = {};
681+
const aba = {};
682+
const ac = {};
683+
const b = {};
684+
685+
tree.insertLast(aa, a);
686+
tree.insertLast(ab, a);
687+
tree.insertLast(aba, ab);
688+
tree.insertLast(ac, a);
689+
tree.insertAfter(b, a);
690+
691+
const results = [];
692+
693+
for (const object of tree.childrenIterator(a)) {
694+
results.push(object);
695+
}
696+
t.deepEqual([aa, ab, ac], results);
697+
698+
t.end();
699+
});
700+
701+
test('children iterator return value using a generator', function(t) {
702+
const tree = new SymbolTree();
703+
const a = {};
704+
const aa = {};
705+
const ab = {};
706+
const ac = {};
707+
708+
tree.insertLast(aa, a);
709+
tree.insertLast(ab, a);
710+
tree.insertLast(ac, a);
711+
712+
function* generator(it) {
713+
const returnValue = yield* it;
714+
t.equal(a, returnValue);
715+
}
716+
717+
const results = [];
718+
719+
for (const object of generator(tree.childrenIterator(a))) {
720+
results.push(object);
721+
}
722+
t.deepEqual([aa, ab, ac], results);
723+
724+
t.end();
725+
});
726+
676727
test('treeToArray', function(t) {
677728
const tree = new SymbolTree();
678729
const a = {};

0 commit comments

Comments
 (0)