Skip to main content
Loading...

More JavaScript Posts

function filePath(file){
  let folders = file.getParents();
  const parents = [];

  function makePathString(folderArray){
    let path = "";
    folderArray.forEach((folder)=>{
      path += "/" + folder.getName();
    });
    return path;
  }
  
  while (folders.hasNext()) {
    const folder = folders.next(); //This should hopefully remove that folder from the iterator
    parents.unshift(folder);
  }

  return makePathString(parents);
}

function myFunction() {
  const myEmail = Session.getEffectiveUser().getEmail();
  Logger.log("My email is " + myEmail);
  // Log the name of every file in the user's Drive.
  var fileIterator = DriveApp.getFiles();
  const files = []; //List of [File, size] entries
  const filesMaxSize = 10;
  while (fileIterator.hasNext()) {
    var file = fileIterator.next();

    const owner = file.getOwner();

    //Only files I own
    if((!(owner)) || (!(owner.getEmail)) || owner.getEmail() != myEmail){
      continue;
    }

    const entry = [file, file.getSize()];

    function slideUp(arr, index){
      //Let's keep sliding it up so we don't have to sort it at the end.
      for(let i = index; i > 0; --i){ //Stops at 1
        const nextFile = arr[i-1];

        if(nextFile[1] > entry[1]){
          break;
        }else{
          //Swap with the next file to slide the file up
          const temp = arr[i];
          arr[i] = arr[i - 1];
          arr[i - 1] = temp;
        }
      }
    }

    if(files.length < filesMaxSize){
      files.push(entry);

      slideUp(files, files.length - 1);
    }else{
      if(entry[1] > files[files.length - 1][1]){ //If it's bigger than the smallest file in the list.
        files[files.length - 1] = entry;  //Replace the smallest file

        slideUp(files, files.length - 1); //Slide it up
      }
    }
  }

  for(let i = 0; i < filesMaxSize; ++i){
    const file = files[i][0];
    const size = files[i][1];
    Logger.log(size + "\t" + filePath(file) + "/" + file.getName() + "\t" + file.getOwner().getName());
  }
}
class TreeNode {
  constructor(key, value = key, parent = null) {
    this.key = key;
    this.value = value;
    this.parent = parent;
    this.children = [];
  }

  get isLeaf() {
    return this.children.length === 0;
  }

  get hasChildren() {
    return !this.isLeaf;
  }
}

class Tree {
  constructor(key, value = key) {
    this.root = new TreeNode(key, value);
  }

  *preOrderTraversal(node = this.root) {
    yield node;
    if (node.children.length) {
      for (let child of node.children) {
        yield* this.preOrderTraversal(child);
      }
    }
  }

  *postOrderTraversal(node = this.root) {
    if (node.children.length) {
      for (let child of node.children) {
        yield* this.postOrderTraversal(child);
      }
    }
    yield node;
  }

  insert(parentNodeKey, key, value = key) {
    for (let node of this.preOrderTraversal()) {
      if (node.key === parentNodeKey) {
        node.children.push(new TreeNode(key, value, node));
        return true;
      }
    }
    return false;
  }

  remove(key) {
    for (let node of this.preOrderTraversal()) {
      const filtered = node.children.filter(c => c.key !== key);
      if (filtered.length !== node.children.length) {
        node.children = filtered;
        return true;
      }
    }
    return false;
  }

  find(key) {
    for (let node of this.preOrderTraversal()) {
      if (node.key === key) return node;
    }
    return undefined;
  }
}

const tree = new Tree(1, 'AB');

tree.insert(1, 11, 'AC');
tree.insert(1, 12, 'BC');
tree.insert(12, 121, 'BG');

[...tree.preOrderTraversal()].map(x => x.value);
// ['AB', 'AC', 'BC', 'BCG']

tree.root.value;              // 'AB'
tree.root.hasChildren;        // true

tree.find(12).isLeaf;         // false
tree.find(121).isLeaf;        // true
tree.find(121).parent.value;  // 'BC'

tree.remove(12);

[...tree.postOrderTraversal()].map(x => x.value);
// ['AC', 'AB']
class TreeNode {
  constructor(data, depth) {
    this.data = data;
    this.children = [];
    this.depth = depth;
  }
}

function buildNaryTree(hosts) {
  const nodeMap = {};

  // Step 1: Create a map of nodes using fqdn as the key
  hosts.forEach((host) => {
    nodeMap[host.fqdn] = new TreeNode(host, 0); // Initialize depth to 0
  });

  // Step 2: Iterate through the array and add each node to its parent's list of children
  hosts.forEach((host) => {
    if (host.displayParent) {
      if (nodeMap[host.displayParent]) {
        const parent = nodeMap[host.displayParent];
        const node = nodeMap[host.fqdn];
        node.depth = parent.depth + 1; // Update the depth
        parent.children.push(node);
      } else {
        console.error(`Parent with fqdn ${host.displayParent} not found for ${host.fqdn}`);
      }
    }
  });

  // Find the root nodes (nodes with no parent)
  const rootNodes = hosts.filter((host) => !host.displayParent).map((host) => nodeMap[host.fqdn]);

  return rootNodes;
}

function treeToObjects(node) {
  const result = [];

  function inOrder(node) {
    if (!node) {
      return;
    }

    
    // Visit the current node and add it to the result
    result.push(node.data);

    // Visit children nodes first
    node.children.forEach((child) => {
      inOrder(child);
    });
  }

  inOrder(node);
  return result;
}

// Usage example
const hosts = [
  {
    fqdn: 'fqdn_1',
    display_name: 'Host 1',
  },
  {
    fqdn: 'fqdn_2',
    display_name: 'Host 2',
    displayParent: 'fqdn_1',
  },
  {
    fqdn: 'fqdn_3',
    display_name: 'Host 3'
  },
  {
    fqdn: 'fqdn_4',
    display_name: 'Host 4',
    displayParent: 'fqdn_3',
  },
  {
    fqdn: 'fqdn_5',
    display_name: 'Host 5',
    displayParent: 'fqdn_1',
  },
];

const tree = buildNaryTree(hosts);

// Function to convert the tree to an array of objects
function convertTreeToArray(nodes) {
  const result = [];
  nodes.forEach((node) => {
    result.push(...treeToObjects(node));
  });
  return result;
}

// Convert the tree back to an array of objects
const arrayFromTree = convertTreeToArray(tree);

console.log(arrayFromTree);