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 am using the following code which recursively executes function findWpisInZone(), code works fine, I just wondering if there is any better way to do it in JS,

DomBuilder.prototype = {
            domTree: '',
            findWpis: function () {
                var dataState = dojo.global.xxx.state.data,
                    scope = this;
                for (var zone in dataState) {
                    for (var wpi in dataState[zone]) {
                        this.domTree += '<div data-xxx-type="{0}">'.format(zone);
                        findWpisInZone(dataState[zone][wpi]);
                        this.domTree += '</div>';
                    }
                }
                function findWpisInZone(wpi, type) {
                    scope.domTree += '<div data-xxx-type="{0}">'.format(wpi.wpi.webpart_cid);
                    for (var zone in wpi.zones) {
                        scope.domTree += '<div data-xxx-type="{0}">'.format(zone)
                        for (var wpiInner in wpi.zones[zone]) {
                            // recursion search
                            findWpisInZone(wpi.zones[zone][wpiInner], type);
                        }
                        scope.domTree += '</div>';
                    }
                    scope.domTree += '</div>';
                }
            },
share|improve this question

1 Answer 1

up vote 1 down vote accepted

I think what you've got here is looking pretty fine. You could move the comment explaining that it's recursive to the function header if you want it to be more explicit. The recursive function isn't doing anything strange, though.

Usually, with recursion, one can unroll the recursion to be iteration instead.

I wouldn't recommend that in this case. Right now, you have about 10-12 lines, depending on how you count. It's just two forloops. The whole function can be summarized as "make a div that contains, for each wpi zone, another div containing it's sub wpi's, similar to the div we make now."

If you were to unroll this recursion then it would get messy.

You did well.


Possible improvements are assigning the strings to separate constants, and perhaps storing wpi.zones[zone] in a local store to reduce a double double array access for each for-loop iteration to a double single array access (the for loop accesses [zone][0] and [zone][wpiInner], by storing [zone] locally, you reduce the accesses to [0] and [wpiInner] instead).

share|improve this answer
    
I appreciate your comments! –  GibboK Dec 11 '14 at 11:08

Your Answer

 
discard

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.