Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.)

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.