user3284007
user3284007

Reputation: 1717

Recursive Function Causing Overflow

I am trying to write a recursive function in JavaScript. My function needs to search a tree of items. I have created a JSFiddle. When I run the JavaScript in Chrome, I get an error that says:

RangeError: Maximum call stack size exceeded

I assume this means that I'm not returning my value at the correct time. However, I continue to review the function and it looks correct to me. What am I doing wrong?

var sitemap = [
  {
    name: 'dashboards', children: [
      { name: 'dashboard 1', route: '/dashboards/dashboard1', html: '' }
    ]
  },
  {
    name: 'objects', children: [
      { name: 'players', route: '/objects/players', html: '/objects/players.html' },
      { name: 'teams', route: '/objects/teams', html: '/objects/teams.html' },
      { name: 'coaches', route: '/objects/coaches', html: '/objects/coaches.html' },
      { name: 'cities', children: [
        { name: 'Chicago', route: '/cities/chicago',
                 html: '/objects/cities/chicago.html' },
        { name: 'Philadelphia', route: '/cities/philadelphia', html: '/objects/cities/philadelphia.html' }
]},                    
        ]
    }
];

var getFromSitemap = function (path, entries) {
    var sitemapItem = null;
    if (entries) {
        angular.forEach(sitemap, function (entry, key) {
            if (entry.hasOwnProperty("children")) {
                sitemapItem = getFromSitemap(path, entry.children);
            } else if (entry.route === path) {
                sitemapItem = entry;
            }
        });
    }
    return sitemapItem;
};

    var getItem = function() {    
var item = getFromSitemap('/cities/chicago', sitemap);
console.log(item);      
    }

Thank you!

Upvotes: 0

Views: 121

Answers (1)

Paul
Paul

Reputation: 141839

You are calling foreach on the same object (sitemap) everytime:

 angular.forEach(sitemap, function ...

It seems like you want to be calling it on entries recursively

 angular.forEach(entries, function ....

Upvotes: 2

Related Questions