Bryntum Quiz 5

by Alexander Novikov

HTML

<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

JavaScript

/*
5. You are given a following JSON tree structure:

var tree = {
    id          : '1',
    
    children    : [
        {
            id          : '2',
            
            children    : [
                {
                    id          : '5',
                    children    : [
                        {
                            id  : '9'
                        }
                    ]
                },
                {
                    id  : '6'
                }
            ]
        },
        {
            id          : '3',
            
            children    : [
                {
                    id  : '7'
                },
                {
                    id  : '8'
                }
            ]
        },
        {
            id  : '4'
        }
    ] 
}

Write the iterator function using pure JavaScript, which will call the provided “func” for each node in the tree, so the following console output will be correct:

var iterator = function (root, func) {
    ...
}

iterator(tree, function (node) {
    console.log(node.id)
})

>>Output:
1
2
3
4
5
6
7
8
9
*/

var tree = {
    id: '1',
    
    children: [
        {
            id: '2',
            
            children: [
                {
                    id : '5',
                    children: [
                        {
                            id: '9'
                        }
                    ]
                },
                {
                    id: '6'
                }
            ]
        },
        {
            id: '3',
            
            children: [
                {
                    id: '7'
                },
                {
                    id: '8'
                }
            ]
        },
        {
            id: '4'
        }
    ] 
};

var iterator = function (node, func) {
    
    var isRoot = false, depth, layers;

    if (typeof arguments[2] === 'undefined' && typeof arguments[3] === 'undefined') {
        depth = 0;
       ...