Skip to content

Instantly share code, notes, and snippets.

@igor9silva
Last active June 18, 2023 02:18
Show Gist options
  • Save igor9silva/ae939d1a51c9b70144167e1b1f2224f0 to your computer and use it in GitHub Desktop.
Save igor9silva/ae939d1a51c9b70144167e1b1f2224f0 to your computer and use it in GitHub Desktop.
const tree = {
"type": "",
"children": [
{
"type": "1",
"children": [
{
"type": "1.1",
"children": [
{ "type": "1.1.1", "children": [] },
{ "type": "1.1.2", "children": [] }
]
},
{
"type": "1.2",
"children": [
{ "type": "1.2.1", "children": [] }
]
}
]
},
{ "type": "2", "children": [] }
]
};
function find(tree, path = '', index = 0) {
// test if found
if (tree.type === path) return tree
// uses 'index' to compute child key
const parts = path.split('.')
const childKey = parts.filter((e, i) => i <= index).join('.')
// find the child or throw
const child = tree.children.find(e => e.type === childKey)
if (!child) throw "Not Found"
// recursively look for path with string comparison
return find(child, path, index + 1)
}
// compute the children indexes converting the path to number (and subtracting 1)
const find2 = (tree, path = '') => path .split('.')
.map(e => Number(e) - 1)
.reduce((e, i) => e.children[i] || tree, tree)
console.log('tests: find recursively');
console.log(find(tree) === tree)
console.log(find(tree, '') === tree)
console.log(find(tree, '1') === tree.children[0])
console.log(find(tree, '2') === tree.children[1])
console.log(find(tree, '1.1') === tree.children[0].children[0])
console.log(find(tree, '1.2') === tree.children[0].children[1])
console.log(find(tree, '1.2.1') === tree.children[0].children[1].children[0])
console.log('tests: find by computing indexes');
console.log(find2(tree) === tree)
console.log(find2(tree, '') === tree)
console.log(find2(tree, '1') === tree.children[0])
console.log(find2(tree, '2') === tree.children[1])
console.log(find2(tree, '1.1') === tree.children[0].children[0])
console.log(find2(tree, '1.2') === tree.children[0].children[1])
console.log(find2(tree, '1.2.1') === tree.children[0].children[1].children[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment