Skip to content

Instantly share code, notes, and snippets.

@Nullpo
Last active November 6, 2015 15:13
Show Gist options
  • Select an option

  • Save Nullpo/19f6ed63e9d6f420493e to your computer and use it in GitHub Desktop.

Select an option

Save Nullpo/19f6ed63e9d6f420493e to your computer and use it in GitHub Desktop.
Find & return node in a tree (maybe in a functional way)
const findInTree =
(fnEquals) => (id, node) =>
fnEquals(node,id) || node.childs.reduce(
(prev, elem) => prev || findInTree(equals)(id, elem), null
);
const tree = {
_id: "1",
name: "alice",
childs: [{
_id: "2",
name: "bob",
childs: []
},{
_id: "3",
name: "carol",
childs: [{
_id: "4",
name:"erin",
childs: []
}]
}];
const myComparator = (node, id) => node._id == id? node : false;
// Call to funciton
findInTree(myComparator)("3", tree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment