Last active
November 6, 2015 15:13
-
-
Save Nullpo/19f6ed63e9d6f420493e to your computer and use it in GitHub Desktop.
Find & return node in a tree (maybe in a functional way)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const findInTree = | |
| (fnEquals) => (id, node) => | |
| fnEquals(node,id) || node.childs.reduce( | |
| (prev, elem) => prev || findInTree(equals)(id, elem), null | |
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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