Created
April 9, 2018 18:26
-
-
Save biera/ca6f315806037816e6270a2313748814 to your computer and use it in GitHub Desktop.
Prune tree
This file contains 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
function prune(tree, condition) | |
{ | |
const children = tree.children | |
.map( | |
tree => prune(tree, condition) | |
) | |
.filter( | |
tree => tree != null | |
); | |
return (condition(tree) || children.length > 0) | |
? Object.assign({}, tree, { children: children }) | |
: null; | |
} | |
function includes(string) { | |
return ({ name }) => name.includes(string); | |
} | |
const deps = { | |
name: "Overall", | |
children: [ | |
{ | |
name: "England", | |
children: [ | |
{ | |
name: "London", | |
children: [ | |
{ | |
name: "Manu", | |
children: [ | |
] | |
}, | |
] | |
}, | |
{ | |
name: "Manchester", | |
children: [ | |
] | |
}, | |
] | |
}, | |
{ | |
name: "Poland", | |
children: [ | |
{ | |
name: "Lądek Zdroj", | |
children: [ | |
] | |
}, | |
] | |
}, | |
] | |
}; | |
let pruned = prune( | |
deps, includes("an") | |
); | |
console.log( | |
JSON.stringify( | |
{ i: deps, p: pruned } | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment