TreeWalker Object Tree Demo
by actualwave
HTML
<script src="https://rawgit.com/burdiuz/mythology_demo_data/master/unaliased_genealogical_tree.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@actualwave/dom-console@0.0.2/console.css">
<script src="https://unpkg.com/@actualwave/dom-console@0.0.2/console.js"></script>
<script src="https://unpkg.com/@actualwave/tree-walker@1.0.6/dist/tree-walker.min.js"></script>
<script src="https://unpkg.com/@actualwave/walker-property-handlers@0.0.1/index.min.js"></script>
<script src="https://unpkg.com/@actualwave/walker-children-adapter@0.1.4/index.min.js"></script>
JavaScript
const {
create,
addAugmentations,
nodeAugmentations,
listAugmentations,
setNamePrefix,
} = TreeWalker;
const {
createHandlers,
} = WalkerPropertyHandlers;
const createAdapter = ChildrenAdapter.default;
// add node augmentations
addAugmentations(nodeAugmentations);
// add list augmentations
addAugmentations(listAugmentations);
/*
data has "label" properties instead of "name",
so we will rewrite getName() adapter method
*/
const adapter = createAdapter(
(item) => item.label.match(/^[\w\s]+/)[0].trim()
);
/*
add a name prefix for node fields to access them easier
before: node.valueOf().label
after: node.$label
*/
setNamePrefix('$', createHandlers());
/*
Source data for the tree
https://rawgit.com/burdiuz/mythology_demo_data/master/unaliased_genealogical_tree.js
*/
const root = create(window.genealogical_tree, adapter);
const { log, info } = DOMConsole.create(document.body);
// root now contains tree walker instance and ready to go
info('The root of all is:');
log(root.valueOf());
info('Lets reach one of its siblings:');
log(root.Gaia['The Titans'].Cronus.Zeus.Perseus.first().valueOf());
info('All the children of Chaos are:');
log(root.children().map((item) => item.$label));
log(root.children().length(), 'in total');
info('Lets find Cratos:');
log(root.descendants('Cratos').first().valueOf());
log(root.descendants('Cratos').length(), ' nodes for Cratos');
log('Its parents are:', root.descendants('Cratos').$parents);
info('And find Ares:');
log(root.descendants('Ares').first().valueOf());
log(root.descendants('Ares').length(), ' nodes for Ares');
log('Its parents are:', root.descendants('Ares').$parents);