2
\$\begingroup\$

I am creating routes from an array of menuItems. I have written a recursive function, which works fine but I think the code can be improved. So, I need you guys to review my code and suggest me some changes.

Here is the code:

const accumulator = [];
const renderRoutes = (_menuItems) => {
  _menuItems.forEach((menuItem) => {
    accumulator.push(
      <Route
        exact
        path={menuItem.path}
        render={props => (
          <Scene
            {...props}
            menuItem={menuItem}
          />
        )}
      />,
    );
    if (menuItem.children) {
      renderRoutes(menuItem.children);
    }
  });
  return accumulator;
};
\$\endgroup\$
1
  • \$\begingroup\$ One simple recommendation would be to not use recursion. \$\endgroup\$
    – slepic
    Nov 22, 2019 at 7:43

1 Answer 1

2
\$\begingroup\$

Avoid recursion, avoid putting the accumulator out of the function that fills it.

My favourite phrase: Every recursive algorithm can be rewritten without recursion. In worst case, using one (extra) stack.

function renderRoutes(menuItems) {
  let accumulator = [];
  let queue = [];
  queue.concat(menuItems);
  while (queue.length > 0) {
    const item = queue.shift();
    accumulator.push(route(item))
    queue.concat(item.children);
  }
  return accumulator;
}

The route(item) is the same as your <Route....

\$\endgroup\$
4
  • \$\begingroup\$ Thank for suggesting the solution. I took a look at your solution. I will implement it. But a question: Why should we avoid recursion? \$\endgroup\$
    – Vishal
    Nov 22, 2019 at 8:16
  • 1
    \$\begingroup\$ @Vishal Recursion puts all stuff onto the implicit stack.Usualy at least some of the data is not necesary to be there.And in most cases you cannot change the size of implicit stack.While you can allow explicit stack to have size whatever you have memory for. In general (not sure in js) recursion deepening may be restricted to some level. Also every call introduces a jump, which is (minor) performance drop. Explicit stack will often reduce the memory consumption greatly and improve performance slightly. Some recursive algorithms can even be implemented entirely without stack (but not your case) \$\endgroup\$
    – slepic
    Nov 22, 2019 at 8:42
  • 1
    \$\begingroup\$ @Vishal the only advantage of recursive algorithms is that they are intuitively easy to write and understand. But nonrecursive variant will always be better in terms of memory and time complexity. (Well you can Always screw up but if everything Is done properly, it Will be better) \$\endgroup\$
    – slepic
    Nov 22, 2019 at 9:00
  • \$\begingroup\$ Got it! Thank you for the explanation. \$\endgroup\$
    – Vishal
    Nov 22, 2019 at 9:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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