I'm using an infinite-level structure, similar to this:
{
"name": "Group1",
"type": "group",
"nodes": [
{
"name": "Node1",
"type": "node",
"someproperty": "somevalue1"
},
{
"name": "Group2",
"type": "group",
"nodes": [
{
"name": "Node2",
"type": "node",
"someproperty": "somevalue2"
},
{
"name": "Node3",
"type": "node",
"someproperty": "somevalue3"
}
]
}
]
}
Where we can have nodes inside groups, but also groups inside groups.
So far I've been writing recursive functions every time I need to do something, but the code is becoming quite unweildly.
I wondered if there was a way to create versions of Array.prototype methods but customise them to use recursion
e.g.to find any object (node or group) by id, I have a method
findNode(target, thisGroup) {
if (typeof thisGroup == "undefined") {
thisGroup = this;
}
// Am I the element?
if (thisGroup.id == target) {
return thisGroup;
}
// Look for element in my nodes
var elementIx = thisGroup.nodes.findIndex(e => e.id == target);
if (elementIx > 0) {
// Found the element - return it
return thisGroup.nodes[elementIx];
}
// Not found. Do I contain a group?
var elementIx = thisGroup.nodes.findIndex(e => e.type == "group");
if (elementIx > 0) {
var nestGroup = thisGroup.nodes[elementIx];
// If so, nest into this group and look again
return this.findValue(target, nestGroup)
}
}
In the real world there's more than just Id I need to search/nest for. So how might I create my own prototype functions which I can then call like this?
thisGroup.nodes.findIndexRecursively(e => e.id == target)
thisGroup.nodes.findIndexRecursively(e => e.type=="node" && e.someProp == someValue)
Array? where isthispointing to? maybe an instanciable or class is better for an object along with another for collections.nodes, you could just make a nodesclassthat extendsArray: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…