TreeModel

by itsazzad

HTML

<script src="https://unpkg.com/[email protected]/dist/TreeModel-min.js"></script>

JavaScript

// hint: TreeModel, tree and root are
// globally available on this page
var tree = new TreeModel();
var root = tree.parse({
});
function treeParse(model){
  root = tree.parse(model);
}
function treeFirst(nodeID){
  return root.first(function (node) {
      return node.model.id === nodeID;
  });
}
function treeAddChild(parentId, childId){
  var parent = treeFirst(parentId);
  //Ask parent to remove all the siblings
  parent.all(function (node) {
      //return not parent, i.e: children
      return node.model.id !== parentId;
  }).forEach(function (node) {
    node.drop();
  });
  parent.addChild(tree.parse({id: childId}));
}
//console.log(treeFirst('Sun'));
treeParse({
  id: 'Sun',
});

treeParse({
  id: 'Earth',
});

treeAddChild('Earth', 'Afro-Eurasia');
treeAddChild('Afro-Eurasia', 'Africa');
treeAddChild('Afro-Eurasia', 'Eurasia');
treeAddChild('Eurasia', 'Asia');
treeAddChild('Eurasia', 'Europe');
treeAddChild('Earth', 'America');
treeAddChild('America', 'North America');
treeAddChild('America', 'South America');
treeAddChild('Earth', 'Antarctica');
treeAddChild('Earth', 'Australia');

console.info(root.model);

treeParse({
  id: 'Moon',
});