Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Iterable tree class by @Orangetronic

Instantiate this class around a tree-like object, e.g.

const filetree = new IterableTree({
  name : "Desktop",
  children : [
   { name : "funny.gif" },
   { name : "resume.pdf" },
   { name : "memes",
     children : [
      { name : "distracted-boyfriend.png" },
      { name : "bröther-may-i-have-some-oats.png" },
      { name : "galaxy-brain.png" },
     ]
   },
   { name : "screenshots",
     children : [
      { name : "screenshot-12-04-2019.png" },
      { name : "screenshot-14-04-2019.png" },
      { name : "screenshot-15-04-2019.png" }
     ]
   }
  ]
})

You can then iterate through your tree like this:

console.log("Your desktop contains the following nonsense")
for (const node of filetree) {
  const nodeType = node.children == null ? "file" : "folder"
  console.log(`${nodeType}: ${node.name}`)
}

You can even spread it into an array

const myFilesAndFolders = [...filetree]
class IterableTree {
constructor(tree) {
this.tree = tree;
}
*[Symbol.iterator]() {
const treeReducer = (accumulator, node) => [
...accumulator,
node,
...(node.children || []).reduce(treeReducer, [])
];
yield* [this.tree].reduce(treeReducer, []);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.