Anatsu
Anatsu

Reputation: 364

Flattening empty group on tree in my nodeJS app

I need your'e help creating a function that will flatten empty groups and move it's users back to it's father. The groups are objects and thei'r children are in an array.

the users are created as objects in a class constructor

user.js

   class User {
  constructor(name, password, age) {
    this.name = name;
    this.password = password;
    this.age = age;
   }
      }

users.js

 class users {
    constructor() {
      this.users = {}
     }

And attached to groups also in a class contractor.

group.js

    class Group {
   constructor(name, parent) {
    this.name = name;
    this.parent = parent || null;
    this.children = [];
    this.users = {}
      }

groups.js

  class groups {
  constructor() {
    this.root = new Group('root');
     }

So if the group's name is bar and the username is foo the log you receive is similar to that:

   Group {name:"root",parent:,children:,users:) chidren: "bar" user: USER 
  {name: "foo",password: "1010",age: "1010"}.

edit i think the way i want to do it is: get the group name, find it's father, check if the father have only one child, reset father's array (length = 0)

only if it's having one child you can continue. check if the group has children, if there are, for each on them and tell them that the group is ther'e new father. push the children to parent's array.

Upvotes: 0

Views: 48

Answers (1)

Fabio Lolli
Fabio Lolli

Reputation: 889

Did not test it, but it should get the job done:

const loopTree = (tree) => {
    if (tree.parent) { //if the element has no parent, no use checking if I should move to parent
        let usersToUp = tree.children.length > 0 ? {} : tree.users; //if children has no items, then the users object is the users object, otherwise an empty object
        Object.assign(tree.parent.users, usersToUp) //assign the users to the parent... No conditional here, if usersToUp is an empty object then this will do nothing.
        if (usersToUp.keys().length > 0) { //and here I remove users from current tree, if there were users to move
            tree.users = {};
        }
    }
    tree.children.forEach(loopTree); //now I just call the same function for other children of the tree
}

Starting from the top group, if it has a parent, check for users to move, and move them. Then proceed to process elements in the lower level.

Since it acts on object references, it should not need any return statement.

Upvotes: 1

Related Questions