Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Total Headcount #5

Open
SteveStephenson-Rios opened this issue Jan 2, 2025 · 1 comment
Open

Total Headcount #5

SteveStephenson-Rios opened this issue Jan 2, 2025 · 1 comment

Comments

@SteveStephenson-Rios
Copy link

I wanted to see if it’s possible to get a total headcount of a node. This headcount would include both direct and indirect reports. Direct reports are currently accounted for as children, but I’m unsure how to account for indirect reports, such as children of children (which could be infinite).

@n1crack
Copy link
Owner

n1crack commented Jan 3, 2025

I think getting the counts from backend is best, but you can try to count children recursively.

function computeChildrenCount(categories) {
  // Map to store children for each category
  const childrenMap = {};

  // Initialize children count
  categories.forEach(category => {
    childrenMap[category.id] = [];
  });

  // Build children relationships
  categories.forEach(category => {
    if (category.parent_id !== null) {
      childrenMap[category.parent_id].push(category.id);
    }
  });

  // Function to recursively count children
  function countChildren(id) {
    return childrenMap[id].reduce(
      (count, childId) => count + 1 + countChildren(childId),
      0
    );
  }

  // Add total_children to each category
  return categories.map(category => ({
    ...category,
    total_children: countChildren(category.id)
  }));
}

const categories = [
  { id: 1, name: "Electronics", parent_id: null },
  { id: 2, name: "Phones", parent_id: 1 },
  { id: 3, name: "Laptops", parent_id: 1 },
  { id: 4, name: "Smartphones", parent_id: 2 },
  { id: 5, name: "Gaming Laptops", parent_id: 3 },
  { id: 6, name: "Accessories", parent_id: 1 },
  { id: 7, name: "Chargers", parent_id: 6 }
];

const result = computeChildrenCount(categories);
console.log(result);

And the output will be:


[
  { "id": 1, "name": "Electronics", "parent_id": null, "total_children": 6 },
  { "id": 2, "name": "Phones", "parent_id": 1, "total_children": 1 },
  { "id": 3, "name": "Laptops", "parent_id": 1, "total_children": 1 },
  { "id": 4, "name": "Smartphones", "parent_id": 2, "total_children": 0 },
  { "id": 5, "name": "Gaming Laptops", "parent_id": 3, "total_children": 0 },
  { "id": 6, "name": "Accessories", "parent_id": 1, "total_children": 1 },
  { "id": 7, "name": "Chargers", "parent_id": 6, "total_children": 0 }
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants