I want to add a parent reference to a tree like structure. The structure can be seen in the first code snippet, which also is how I would use my code, for example inside an angular controller.
$scope.tree = Tree.parentize({
title: 'root',
children: [{
title: 'child one',
children: [{
title: 'leaf one',
children: []
}, {
title: 'leaf two',
children: []
}, {
title: 'leaf three',
children: []
}]
}, {
title: 'child two',
children: [{
title: 'leaf four',
children: []
}, {
title: 'leaf five',
children: []
}]
}]
});
This is how I implemented the parentize()
function.
'use strict';
var Tree = (function () {
var parentize = function(tree) {
angular.forEach(tree.children, function(value, key) {
this.children[key].parent = function() {
return tree;
};
parentize(value);
}, tree);
return tree;
};
return {
parentize: parentize
};
})();
I chose to use a function, to still be able to use JSON.stringify()
without need for the replacer argument. It works as expected. But is it the right approach? Is instantiation of a function for each node to heavy? The tree will probably not have more than 500 nodes.
I tried to follow the module pattern. Did I do anything wrong here? Also I'm not sure about "not polluting the global namespace". Is it wrong for Tree
to be global? Should Tree
be provided via angular as a service, or factory?
(jsHint warns about 'Tree' is not defined in my controller.js. However adding Tree
to the predef list, it warns about Redefinition of 'Tree' in my tree.js.)