1
\$\begingroup\$

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>';
                }
            },
\$\endgroup\$
1
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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