Skip to content

Commit 5fb2c81

Browse files
Method to look up the node index of an object
1 parent 6b84fdd commit 5fb2c81

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

lib/SymbolTree.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,40 @@ class SymbolTree {
460460
return iterator;
461461
}
462462

463+
/**
464+
* Find the index of the given object (the number of preceding siblings).
465+
*
466+
* `O(n)`
467+
*
468+
* @method index
469+
* @memberOf module:symbol-tree#
470+
* @param {Object} child
471+
* @return {Number} The number of preceding siblings, or -1 if the object has no parent
472+
*/
473+
index(child) {
474+
const parentNode = this._node(this._node(child).parent);
475+
476+
if (!parentNode) {
477+
// In principal, you could also find out the number of preceding siblings
478+
// for objects that do not have a parent. This method limits itself only to
479+
// objects that have a parent because that lets us optimize more.
480+
return -1;
481+
}
482+
483+
let index = 0;
484+
let object = parentNode.first;
485+
486+
while (object) {
487+
if (object === child) {
488+
break;
489+
}
490+
++index;
491+
object = this._node(object).next;
492+
}
493+
494+
return index;
495+
}
496+
463497
/**
464498
* Remove the object from this tree.
465499
* Has no effect if already removed.

test/SymbolTree.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -893,3 +893,28 @@ test('tree iterator', function(t) {
893893

894894
t.end();
895895
});
896+
897+
test('look up the index of an object', function(t) {
898+
const tree = new SymbolTree();
899+
const a = {};
900+
const aa = {};
901+
const ab = {};
902+
const aba = {};
903+
const ac = {};
904+
const b = {};
905+
906+
tree.insertLast(aa, a);
907+
tree.insertLast(ab, a);
908+
tree.insertLast(aba, ab);
909+
tree.insertLast(ac, a);
910+
tree.insertAfter(b, a);
911+
912+
t.equal(-1, tree.index(a), 'should return -1 if an object has no parent');
913+
t.equal(0, tree.index(aa));
914+
t.equal(1, tree.index(ab));
915+
t.equal(0, tree.index(aba));
916+
t.equal(2, tree.index(ac));
917+
t.equal(-1, tree.index(b));
918+
919+
t.end();
920+
});

0 commit comments

Comments
 (0)