I am trying to traverse a tree and create a Map data structure that holds only the first parent of the elements . key{child element} : value {array of 1st parents}
My code
global.parentMap = new Map()
function readTree(root) {
let queue = [root];
while (queue.length > 0) {
let node = queue.shift();
for (let childType in node.children) {
for (let child of node.children[childType]) {
let newChild = {...child};
queue.push(newChild);
if(global.parentMap.has(newChild.item.name)){
global.parentMap.set(newChild.item.name,global.parentMap.get(newChild.item.name).push(node.item.name))}
if(!parentMap.has(newChild)){
global.parentMap.set(newChild.item.name,[]);
}
console.log("Parent" node.item.name " has childs " newChild.item.name)
global.parentMap.get(newChild.item.name).push(node.item.name);
}
}
}
}
The issue is that the new global does not push parents as a value to the Map data structure and it is always overridden
Console output
Parent : testing_group has childs:command_name
Parent : agv_commands has childs:location_name
Parent : agv_commands has childs:header_frame_id
Parent : agv_commands has childs:location_coordinates
Parent : agv_commands has childs:robot_name
Parent : agv_commands has childs:load_id
Parent : agv_commands has childs:command_item
Parent : agv_commands has childs:command_name
Map(7) {
'command_name' => [ 'agv_commands' ], // it should include testing_group
'location_name' => [ 'agv_commands' ],
'header_frame_id' => [ 'agv_commands' ],
'location_coordinates' => [ 'agv_commands' ],
'robot_name' => [ 'agv_commands' ],
'load_id' => [ 'agv_commands' ],
'command_item' => [ 'agv_commands' ]
}
CodePudding user response:
There are these issues:
The following code defines a Map entry as an integer, not an Array:
global.parentMap.set(newChild.item.name, global.parentMap.get(newChild.item.name).push(node.item.name))
...because
push
does not return an array, it first mutates the array, but then returns an integer (the length of the array), which you then set as Map value.This code should just be removed, as a few statements further down, it is done correctly with:
global.parentMap.get(newChild.item.name).push(node.item.name);
parentMap
is here accessed without theglobal.
prefix, which is not really a problem, but is inconsistent with the rest of the code:if(!parentMap.has(newChild))
In the same expression, the
has
method is getting an object as argument, while yourMap
is keyed by strings. So change it to:if(!global.parentMap.has(newChild.item.name))
With those fixes it should work.