Skip to content

Commit f77e8ad

Browse files
Convert all children to an array
1 parent cec9cb7 commit f77e8ad

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

lib/SymbolTree.js

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,29 @@ class SymbolTree {
227227
return null;
228228
}
229229

230+
/**
231+
* Append all children of the given object to an array.
232+
*
233+
* `O(n)`
234+
* @param {Object} object
235+
* @param {Object[]} [array=[]]
236+
* @return {Object[]}
237+
*/
238+
childrenToArray(object, array) {
239+
if (!array) {
240+
array = [];
241+
}
242+
243+
object = this._node(object).first;
244+
245+
while (object) {
246+
array.push(object);
247+
object = this._node(object).next;
248+
}
249+
250+
return array;
251+
}
252+
230253
/**
231254
* Remove the object from this tree.
232255
* Has no effect if already removed.
@@ -414,4 +437,4 @@ class SymbolTree {
414437
}
415438
}
416439

417-
module.exports = SymbolTree;
440+
module.exports = SymbolTree;

test/SymbolTree.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -613,3 +613,27 @@ test('following with skipChildren', function(t) {
613613

614614
t.end();
615615
});
616+
617+
test('childrenToArray', function(t) {
618+
const tree = new SymbolTree();
619+
const a = {};
620+
const aa = {};
621+
const ab = {};
622+
const aba = {};
623+
const ac = {};
624+
const b = {};
625+
626+
tree.insertLast(aa, a);
627+
tree.insertLast(ab, a);
628+
tree.insertLast(aba, ab);
629+
tree.insertLast(ac, a);
630+
tree.insertAfter(b, a);
631+
632+
t.deepEqual([aa, ab, ac], tree.childrenToArray(a));
633+
634+
const arr = ['a', 5];
635+
tree.childrenToArray(a, arr);
636+
t.deepEqual(['a', 5, aa, ab, ac], arr);
637+
638+
t.end();
639+
});

0 commit comments

Comments
 (0)