Удалить все группы и дочерние элементы в приложении nodeJS - PullRequest
0 голосов
/ 14 мая 2018

Мне нужна помощь с моим маленьким приложением nodeJS. Мне нужно создать функцию, которая будет удалять вложенные группы в дереве. Я отладил мою рекурсию поиска по дереву, и она отлично работает. но моя функция удаления ничего не удаляет. мне нужно добраться до родителя и удалить его из массива. дерево выглядит так:

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

функция поиска рабочего дерева (не стесняйтесь использовать!) и не функционирующая функция удаления

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;
    }
}
removeByName(name) {
    if (!this.children)
        return;

    const groupToRemove = this.findGroupByName(name);

    if (groupToRemove) {
        this.children = this.children.filter(g => g !== groupToRemove);
    }
}

обработчик меню

function removeGroup(callback) { //need fixing
    rl.question('Enter group name to delete: \n', (groupName) => {
        let parentGroup = programdata.groups.findGroupByName(groupName);
        programdata.groups.removeByName(groupName)
        console.log(parentGroup);
        callback()
    })
}

function showGroups(callback) {
    callback()
}

1 Ответ

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

Это не работает для вас, потому что группа, возвращаемая _findGroupByNameInternal(), не обязательно является дочерней для экземпляра, который вы назвали removeByName().Поэтому, когда вы пытаетесь filter() экземпляры детей, его может не быть - это может быть внук или глубже.Вам нужно удалить группу, когда вы найдете ее и все еще знаете родителя.Есть много способов сделать это, но вот простой:

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

class Group {
    constructor(name, parent) {
        this.name = name;
        this.parent = parent || null;
        this.children = [];     
    }
    removeByName(name){
        // is name in children?
        let index = this.children.findIndex(g => g.name === name)
        if (index > -1) {
            //  delete it
            this.children.splice(index, 1)
            console.log(`removed ${name} from ${this.name}`)
        } else {
            // otherwise recurse on children
            this.children.forEach(child => child.removeByName(name))
        }
        
    }
}

Вот полный фрагмент:

class Group {
    constructor(name, parent) {
        this.name = name;
        this.parent = parent || null;
        this.children = [];     
    }
    removeByName(name){
        let index = this.children.findIndex(g => g.name === name)
        if (index > -1) {
            this.children.splice(index, 1)
            console.log(`removed ${name} from ${this.name}`)
        } else {
            this.children.forEach(child => child.removeByName(name))
        }
        
    }
}

class Groups {
    constructor() {
      this.root = new Group('root');
    }
    removeByName(name){
        this.root.removeByName(name)
    }
}
let groups = new Groups()

// Make some nested groups
for (let j=0; j < 5; j++){
    let parent = groups.root
    let group = new Group(`group_${j}`, parent )
    parent.children.push(group)
    parent = group
    for (let i=0; i < 5; i++){
        let group = new Group(`group_${j}_${i}`, parent )
        parent.children.push(group)
    }
}

// Delete the second second of group 3 (group_3_1)
groups.removeByName('group_3_1')

// Make sure group_3_1 is gone
console.log(groups.root.children[3].children.map(c => c.name))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...