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}));
}

treeParse({
  id: 'Earth'
});
treeAddChild('Earth', 'Afro-Eurasia');
treeAddChild('Afro-Eurasia', 'Africa');
treeAddChild('Afro-Eurasia', 'Eurasia');
treeAddChild('Eurasia', 'Asia');
console.info(root.model);