Skip to content

Instantly share code, notes, and snippets.

@Orangetronic
Last active May 21, 2019 10:05
Show Gist options
  • Save Orangetronic/d48fc007e3388b527863aa8ba8748c9d to your computer and use it in GitHub Desktop.
Save Orangetronic/d48fc007e3388b527863aa8ba8748c9d to your computer and use it in GitHub Desktop.
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