Hello, I am currently traversing a tree structure recursively. To handle undefined nodes in the tree, I have implemented guards to prevent any failures. However, during the mapping of children nodes, I encountered the following error:
Error Output
Adrian has children: Marian, Dan,
Dan is a leaf
Marian has children: Liviu, Farcas,
t.ngfactory.js?
[sm]:1 ERROR TypeError: Cannot read property 'logRecursive' of undefined
at push../src/app/pages/tree-view/treeview.component.ts.TreeViewComponent.logRecursive (tree-view.component.ts:29)
at Array.map (<anonymous>)
at TreeViewComponent.push../src/app/pages/tree-view/tree-view.component.ts.TreeViewComponent.logRecursive (tree-view.component.ts:29)
at TreeViewComponent.push../src/app/pages/tree-view/tree-view.component.ts.TreeViewComponent.ngOnInit (tree-view.component.ts:37)
at checkAndUpdateDirectiveInline (core.js:18537)
at checkAndUpdateNodeInline (core.js:19801)
at checkAndUpdateNode (core.js:19763)
at debugCheckAndUpdateNode (core.js:20397)
at debugCheckDirectivesFn (core.js:20357)
at Object.eval [as updateDirectives] (TreeViewComponent_Host.ngfactory.js? [sm]:1)
Code Snippet
public logRecursive(model: TreeModel): number {
if (model == null || model === undefined) {
console.log("null");
return 0;
}
if (model.children === undefined || model.children.length == 0){
console.log(`${model.id} is a leaf`);
return 1;
}
console.log(`${model.id} has children: ${model.children.reduce((x,y)=>y.id+","+x,"")}`);
var result = model.children.map(this.logRecursive).reduce((x,y)=>x+y);
return result;
}
Data Model
export interface TreeModel {
id: string;
children: Array<TreeModel>;
}
Note I have tried various guard combinations for handling children being null, undefined, or having a length of zero but the issue still persists on the second level when processing the 'Marian' node's children.
Input Data
let a: TreeModel = {
id: "Adrian",
children: [
{id: "Dan", children: []},
{id: "Marian", children: [ // Error occurs here while mapping children...
{id: "Farcas", children: []},
{id: "Liviu", children: []}
]}
]
};
Function Call
logRecursive(a);