Skip to content

Commit 225c7bb

Browse files
Method to convert all descendants to an array
1 parent f77e8ad commit 225c7bb

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

lib/SymbolTree.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,9 @@ class SymbolTree {
231231
* Append all children of the given object to an array.
232232
*
233233
* `O(n)`
234+
*
235+
* @method childrenToArray
236+
* @memberOf module:symbol-tree#
234237
* @param {Object} object
235238
* @param {Object[]} [array=[]]
236239
* @return {Object[]}
@@ -250,6 +253,35 @@ class SymbolTree {
250253
return array;
251254
}
252255

256+
/**
257+
* Append all descendants of the given object to an array (in tree order).
258+
*
259+
* `O(n)`
260+
*
261+
* @method treeToArray
262+
* @memberOf module:symbol-tree#
263+
* @param {Object} root
264+
* @param {Object[]} [array=[]]
265+
* @param {Boolean} [includeRoot=true] Include the given `root` object in the array?
266+
* @return {Object[]}
267+
*/
268+
treeToArray(root, array, includeRoot) {
269+
if (!array) {
270+
array = [];
271+
}
272+
273+
let object = includeRoot || includeRoot === undefined
274+
? root
275+
: this.following(root, root);
276+
277+
while (object) {
278+
array.push(object);
279+
object = this.following(object, root);
280+
}
281+
282+
return array;
283+
}
284+
253285
/**
254286
* Remove the object from this tree.
255287
* Has no effect if already removed.

test/SymbolTree.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -637,3 +637,28 @@ test('childrenToArray', function(t) {
637637

638638
t.end();
639639
});
640+
641+
test('treeToArray', function(t) {
642+
const tree = new SymbolTree();
643+
const a = {};
644+
const aa = {};
645+
const ab = {};
646+
const aba = {};
647+
const abaa = {};
648+
const b = {};
649+
650+
tree.insertLast(aa, a);
651+
tree.insertLast(ab, a);
652+
tree.insertLast(aba, ab);
653+
tree.insertLast(abaa, aba);
654+
tree.insertAfter(b, a);
655+
656+
t.deepEqual([a, aa, ab, aba, abaa], tree.treeToArray(a));
657+
t.deepEqual([aa, ab, aba, abaa], tree.treeToArray(a, null, false));
658+
659+
const arr = ['a', 5];
660+
tree.treeToArray(a, arr);
661+
t.deepEqual(['a', 5, a, aa, ab, aba, abaa], arr);
662+
663+
t.end();
664+
});

0 commit comments

Comments
 (0)