Skip to content

Commit

Permalink
refactor(traverseFunctions.js): add traverseAncestors()
Browse files Browse the repository at this point in the history
  • Loading branch information
sguimmara committed Dec 23, 2024
1 parent 16954db commit 95763dd
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
25 changes: 25 additions & 0 deletions src/base/traverseFunctions.js
Original file line number Diff line number Diff line change
Expand Up @@ -488,3 +488,28 @@ export function toggleTiles( tile, renderer ) {
}

}

/**
* Traverses the ancestry of the tile up to the root tile.
*/
export function traverseAncestors( tile, callback = null ) {

let current = tile;

while ( current ) {

const depth = current.__depth;
const parent = current.parent;

if ( callback ) {

callback( current, parent, depth );

}

current = parent;

}


}
29 changes: 28 additions & 1 deletion test/traverseFunctions.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { traverseSet } from '../src/base/traverseFunctions.js';
import { traverseAncestors, traverseSet } from '../src/base/traverseFunctions.js';

describe( 'traverseSet', () => {

Expand Down Expand Up @@ -99,3 +99,30 @@ describe( 'traverseSet', () => {
} );

} );

describe( 'traverseAncestors', () => {

function makeTile( name, parent = undefined ) {

return { name, parent };

}

it( 'visit all ancestry chain', () => {

const root = makeTile( 'root' );

const lod1 = makeTile( '1', root );
const lod2 = makeTile( '2', lod1 );
const lod3 = makeTile( '3', lod2 );
const lod4 = makeTile( '4', lod3 );

const visited = [];

traverseAncestors( lod4, tile => visited.push( tile.name ) );

expect( visited ).toEqual( [ '4', '3', '2', '1', 'root' ] );

} );

} );

0 comments on commit 95763dd

Please sign in to comment.