Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function drawNestedSetsTree(data, node) {
- if (data.length === 0) {
- return;
- }
- let sortItems = (a, b) => {
- if (a.left > b.left) {
- return 1;
- }
- if (a.left < b.left) {
- return -1;
- }
- };
- data.sort(sortItems);
- let firstItem = data[0];
- const ul = document.createElement('ul');
- node.appendChild(ul);
- let findItem = (items, value, side='left') => {
- let result = null;
- items.forEach((item, index) => {
- if (item[side] === value) {
- result = item;
- return;
- }
- });
- return result;
- }
- let getSiblings = (data) => {
- let siblings = [data[0]];
- let foundSibling = data[0];
- while (foundSibling != null) {
- foundSibling = findItem(data, (foundSibling.right+1), 'left');
- if (foundSibling != null) {
- siblings.push(foundSibling);
- }
- }
- siblings.sort(sortItems);
- return siblings;
- };
- let getChildren = (data, parent) => {
- let children = [];
- data.forEach((item, index) => {
- if (item.left === parent.left + 1) {
- children.unshift(item);
- } else if (item.left > parent.left && item.right < parent.right) {
- children.push(item);
- }
- });
- return children;
- }
- let siblings = getSiblings(data, firstItem);
- siblings.forEach((sibling, index) => {
- let li = document.createElement('li');
- ul.appendChild(li);
- li.textContent = sibling.title;
- let siblingChildren = getChildren(data, sibling);
- drawNestedSetsTree(siblingChildren, li);
- });
- }
- if (typeof module !== 'undefined') {
- module.exports = drawNestedSetsTree;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement