Skip to content

Commit 7065691

Browse files
childrenToArray: Filter function argument
1 parent 1abf50e commit 7065691

File tree

2 files changed

+49
-4
lines changed

2 files changed

+49
-4
lines changed

lib/SymbolTree.js

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -238,19 +238,29 @@ class SymbolTree {
238238
*
239239
* @method childrenToArray
240240
* @memberOf module:symbol-tree#
241-
* @param {Object} object
241+
* @param {Object} parent
242242
* @param {Object[]} [array=[]]
243+
* @param {Function} [filter] Function to test each object before it is added to the array.
244+
* Invoked with arguments (object). Should return `true` if an object
245+
* is to be included.
246+
* @param {*} [thisArg] Value to use as `this` when executing `filter`.
243247
* @return {Object[]}
244248
*/
245-
childrenToArray(object, array) {
249+
childrenToArray(parent, array, filter, thisArg) {
246250
if (!array) {
247251
array = [];
248252
}
249253

250-
object = this._node(object).first;
254+
if (!filter) {
255+
filter = returnTrue;
256+
}
257+
258+
let object = this._node(parent).first;
251259

252260
while (object) {
253-
array.push(object);
261+
if (filter.call(thisArg, object)) {
262+
array.push(object);
263+
}
254264
object = this._node(object).next;
255265
}
256266

test/SymbolTree.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -638,6 +638,41 @@ test('childrenToArray', function(t) {
638638
t.end();
639639
});
640640

641+
test('childrenToArray with filter', function(t) {
642+
const tree = new SymbolTree();
643+
const a = {};
644+
const aa = {};
645+
const ab = {};
646+
const aba = {};
647+
const ac = {};
648+
const b = {};
649+
650+
tree.insertLast(aa, a);
651+
tree.insertLast(ab, a);
652+
tree.insertLast(aba, ab);
653+
tree.insertLast(ac, a);
654+
tree.insertAfter(b, a);
655+
656+
const filter = function(object) {
657+
t.equal(this, undefined);
658+
659+
return object !== ab;
660+
};
661+
662+
t.deepEqual([aa, ac], tree.childrenToArray(a, null, filter));
663+
664+
const thisArg = {a: 123};
665+
const filterThis = function(object) {
666+
t.equal(this, thisArg);
667+
668+
return object !== ab;
669+
};
670+
671+
t.deepEqual([aa, ac], tree.childrenToArray(a, null, filterThis, thisArg));
672+
673+
t.end();
674+
});
675+
641676
test('treeToArray', function(t) {
642677
const tree = new SymbolTree();
643678
const a = {};

0 commit comments

Comments
 (0)