File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff 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.
Original file line number Diff line number Diff 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+ } ) ;
You can’t perform that action at this time.
0 commit comments