Advertisement
Guest User

Untitled

a guest
Jul 25th, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. function drawNestedSetsTree(data, node) {
  2.  
  3. if (data.length === 0) {
  4. return;
  5. }
  6.  
  7. let sortItems = (a, b) => {
  8. if (a.left > b.left) {
  9. return 1;
  10. }
  11. if (a.left < b.left) {
  12. return -1;
  13. }
  14. };
  15.  
  16. data.sort(sortItems);
  17.  
  18. let firstItem = data[0];
  19.  
  20. const ul = document.createElement('ul');
  21. node.appendChild(ul);
  22.  
  23. let findItem = (items, value, side='left') => {
  24. let result = null;
  25. items.forEach((item, index) => {
  26. if (item[side] === value) {
  27. result = item;
  28. return;
  29. }
  30. });
  31. return result;
  32. }
  33.  
  34. let getSiblings = (data) => {
  35. let siblings = [data[0]];
  36. let foundSibling = data[0];
  37.  
  38. while (foundSibling != null) {
  39. foundSibling = findItem(data, (foundSibling.right+1), 'left');
  40. if (foundSibling != null) {
  41. siblings.push(foundSibling);
  42. }
  43. }
  44.  
  45. siblings.sort(sortItems);
  46. return siblings;
  47. };
  48.  
  49. let getChildren = (data, parent) => {
  50. let children = [];
  51. data.forEach((item, index) => {
  52. if (item.left === parent.left + 1) {
  53. children.unshift(item);
  54. } else if (item.left > parent.left && item.right < parent.right) {
  55. children.push(item);
  56. }
  57. });
  58. return children;
  59. }
  60.  
  61. let siblings = getSiblings(data, firstItem);
  62.  
  63. siblings.forEach((sibling, index) => {
  64. let li = document.createElement('li');
  65. ul.appendChild(li);
  66. li.textContent = sibling.title;
  67.  
  68. let siblingChildren = getChildren(data, sibling);
  69.  
  70. drawNestedSetsTree(siblingChildren, li);
  71. });
  72. }
  73.  
  74.  
  75.  
  76. if (typeof module !== 'undefined') {
  77. module.exports = drawNestedSetsTree;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement