Vishal
Vishal

Reputation: 6368

got stuck in recursion return value

I have written a small recursive function to find the level of menuItem. Here is the function:

const getSelectedMenuItemLevel = (menuItems, path, level = 0) => menuItems.forEach((menuItem) => {
  console.log(menuItem.path, path, menuItem.path === path, level);
  if (menuItem.path === path) {
    return level;
  }
  return getSelectedMenuItemLevel(menuItem.children, path, level + 1);
});

This is how I call it:

console.log(getSelectedMenuItemLevel(menuItems, 'two/three'));

Here is the menuItems Array:

[
  {
    path: 'one',
    name: 'One',
    children: [
      { path: 'one/one', name: 'One/One', children: [] },
      { path: 'one/two', name: 'One/Two', children: [] },
    ],
  },
  {
    path: 'two',
    name: 'Two',
    children: [
      { path: 'two/one', name: 'Two/One', children: [] },
      { path: 'two/two', name: 'Two/Two', children: [] },
      { path: 'two/three', name: 'Two/Three', children: [] },
    ],
  },
{
    path: 'three',
    name: 'Three',
    children: [],
  }
]

This recursive function always returns me undefined. I expect it to return level

Upvotes: 2

Views: 55

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386550

You need a variable in the function and store it by checking the iteration for a found level with Array#some, bedcause this method uses a short circuit if a valid level is found.

Basically you need to extend the wanted return values to undefined or to a numerical value.

const getSelectedMenuItemLevel = (menuItems, path, level = 0) => {
    let value;
    menuItems.some((menuItem) => {
        if (menuItem.path === path) {
            value = level;
            return true;
        }
        const temp = getSelectedMenuItemLevel(menuItem.children, path, level + 1);
        if (temp) {
            value = temp;
            return true;
        }
      return false;
    });
    return value;
};


var menuItems = [
  {
    path: 'one',
    name: 'One',
    children: [
      { path: 'one/one', name: 'One/One', children: [] },
      { path: 'one/two', name: 'One/Two', children: [] },
    ],
  },
  {
    path: 'two',
    name: 'Two',
    children: [
      { path: 'two/one', name: 'Two/One', children: [] },
      { path: 'two/two', name: 'Two/Two', children: [] },
      { path: 'two/three', name: 'Two/Three', children: [] },
    ],
  },
{
    path: 'three',
    name: 'Three',
    children: [],
  }
];

console.log(getSelectedMenuItemLevel(menuItems, 'two/three'));

Upvotes: 1

Related Questions