Проблемы с печатью дерева моих групп в приложении nodeJS - PullRequest
0 голосов
/ 15 мая 2018

Я пытаюсь напечатать все созданные группы, и они являются детьми, поэтому это будет выглядеть так:

[ [ 'Father1', 'Child1', 'Child2', 'Child3' ],
  [ 'Father1', 'Child1', 'Child4' ],
  [ 'Father1', 'Child1', 'Child5' ] ]

Проблемы, с которыми я столкнулся, различны.из: var keys = name.keys (o);^ TypeError: name.keys не является функцией для полного переполнения стека, я отлаживал функцию printPath и выполняет свою работу отдельно, но не с моей окончательной структурой дерева.

Мое дерево и функция печати выглядят так:

groups.js:

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



    printPath(name){
        this.root.getPath(name)
    }

group.js:

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



     getPath(name) {
        function iter(o, p)  {
            var keys = name.keys(o);
            if (keys.length) {
                return keys.forEach(function (k) {
                    iter(o[k], p.concat(k));
                });
            }
            result.push(p);
        }

        var result = [];
        iter(name, []);
        return result;
    }

Редактировать: Для создания группы я использую функцию обработчика меню:

function createGroup(callback) {
    rl.question('Add name for father group: \n', (parent) => {
        let parentGroup = programdata.groups.findGroupByName(parent);

        if (!parentGroup) {
            parentGroup = programdata.groups.root;
        }

        rl.question('name of new group\n', (groupName) => {
            parentGroup.setChildren(new Group(groupName, parentGroup));

            console.log(parentGroup);
            callback();
          });
        })
    }

findGroupByName - замечательная рекурсия, которую я сделал, которая находит вложенные группы (не стесняйтесь использовать!) сидя в группах классов.

 findGroupByName(name) {
   if (!name) return null;

   return this._findGroupByNameInternal(this.root, name);
   }


    _findGroupByNameInternal(group, name) {
   if (!group) return null;

   if (group.name === name) return group;

  for (const g of group.children) {
    const result = this._findGroupByNameInternal(g, name);

    if (!result) continue;

    return result;
    }
   }

И функция setChildren помещена в группу классов:

setChildren(child) {
    this.children.push(child);
}

РЕДАКТИРОВАТЬ: СпасибоВы за ответ, не могли бы вы помочь мне реализовать ваш метод в моем обработчике меню?Я попробовал это: и это ничего не дало мне.

 function createGroup(callback) {
 rl.question('Add name for father group: \n', (parent) => {
let parentGroup = programdata.groups.findGroupByName(parent);
let treePath = Group.root.printPath();
if (!parentGroup) {
    parentGroup = programdata.groups.root;
}

rl.question('name of new group\n', (groupName) => {
    parentGroup.addChild(new Group(groupName, parentGroup));

    console.log(treePath);
    callback();
   });
 })
}

Ответы [ 2 ]

0 голосов
/ 15 мая 2018

Хорошо, найдено решение.

  Treeshow(){
    var node = this.root;
    var depth = '-'
    recurse( node );
    function recurse( node) {
        depth +='-'
        console.log(depth+node.name);

        for (var child in node.children ) {
            recurse(node.children[child]);
        }
        depth  = depth.slice(0, -1);
    }
}

, которое покажет мое дерево так:

--root
---FooFather
----BarSemiFather
-----FooChild
------BarBaby
0 голосов
/ 15 мая 2018

Основная причина, по которой вы получили ошибку TypeError: name.keys is not a function, заключается в том, что в getPath(name) в качестве аргумента name передается строка, вы знаете, что строковый объект JS не имеет свойства функции keys .

Я провожу рефакторинг вашего кода и исправляю некоторые ошибки, вот тестируемая версия.Пожалуйста, поместите их в одну папку и запустите test.js.

group.js

class Group {


constructor(name, parent) {
    this.name = name;
    this.parent = parent || null; // Point to this group's father
    this.children = []; // Children of this group, can be sub-group or string
    if (!!parent) { // Link to the father
      parent.addChild(this);
    }
    // this.users = new users || null; // Useless, remove it.
  }

  addChild(...args) {
    for(let o in args) {
      this.children.push(args[o]);
    }
  }

  /**
   * Recursion to build the tree
   * @param group
   * @returns {*}
   */
  iter(group) {
    let children = group.children;
    if (Array.isArray(children)) { // If the child is a group
      if (children.length > 0) {
        let result = [];
        result.push(group.name);
        for (let child of children) {
          result.push(group.iter(child));
        }
        return result;
      }
      else {
        return [];
      }
    }
    else { // If the group is a string
      return group;
    }
  }

  getPath() {
    return this.iter(this);
  }
}

module.exports = Group;

groups.js

let Group = require('./group');

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

  printPath() {
    return this.root.getPath();
  }
}

module.exports = Groups;

test.js

let Group = require('./group');
let Groups = require('./groups');

// Root
let rootGroups = new Groups();

// Group 1
let group1 = new Group('Father1', rootGroups.root);
group1.addChild('Child1', 'Child2', 'Child3');

// Group 2
let group2 = new Group('Father1', rootGroups.root);
group2.addChild('Child1', 'Child4');

// Group 3
let group3 = new Group('Father1', rootGroups.root);
group3.addChild('Child1', 'Child5');

let treePath = rootGroups.printPath();
console.log(treePath);

Вывод:

[ 'root',
  [ 'Father1', 'Child1', 'Child2', 'Child3' ],
  [ 'Father1', 'Child1', 'Child4' ],
  [ 'Father1', 'Child1', 'Child5' ] ]

Process finished with exit code 0

Наслаждайтесь:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...