I have a data structure as depicted below, basically data is an array containing a list of nodes, each node can be connected with a parent node, creating a tree alike structure.
Each node has a rotation_relative property, this it is its relative rotation.
As nodes can be nested at any level I need to calculate property rotation_absolute for every node based on its parents, (I have added the final result for each node in the tree below).
Basically leaves should have a rotation_absolute equals to the sum of their parents in the right path.
Considering that:
- The node in
dataarray can be placed at any order. - There could be an unlimited number of nesting (node inside a node).
- Data could contain hundred of nodes
Could you advice any algorithm to solve the problem?
A
|_B
| |_F (rotation_absolute = -20)
|
|_C
|_D (rotation_absolute = 20)
|_E (rotation_absolute = 40)
X (rotation_absolute = 20)
|_J (rotation_absolute = 0)
|_Y (rotation_absolute = 40)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script>
window.app = {
data: [
{
id: 'j',
parent: 'x',
rotation_relative: 20,
rotation_absolute: null
},
{
id: 'y',
parent: 'x',
rotation_relative: 20,
rotation_absolute: null
},
{
id: 'a',
parent: '',
rotation_relative: 0,
rotation_absolute: null
},
{
id: 'f',
parent: 'b',
rotation_relative: -20,
rotation_absolute: null
},
{
id: 'b',
parent: 'a',
rotation_relative: 0,
rotation_absolute: null
},
{
id: 'e',
parent: 'd',
rotation_relative: 20,
rotation_absolute: null
},
{
id: 'x',
parent: '',
rotation_relative: 20,
rotation_absolute: null
},
{
id: 'c',
parent: 'a',
rotation_relative: 0,
rotation_absolute: null
},
{
id: 'd',
parent: 'c',
rotation_relative: 20,
rotation_absolute: null
},
],
start: function () {
// get root
var get1Level = function (parent) {
var nodes1L = this.data.filter(function (item) {
if (item.parent === parent) {
return true;
} else {
return false;
}
}, this);
return nodes1L;
}.bind(this);
var recursion = function (id) {
var nodes = get1Level(id);
nodes.forEach(function (item) {
console.log(item);
recursion.call(this, item.id);
console.log('--');
}, this);
}.bind(this);
var roots = recursion.call(this, '');
}
};
</script>
</head>
Notes:
I realize the title could be really descriptive, please feel free to suggest me a better one. Thanks all.
This is an example of recursion I am working on but I have some problem with adding of value part.