我的小nodeJS应用程序需要帮助。我需要创建一个删除树中嵌套组的函数。 iv调试了我的树搜索递归,效果很好。 但我的删除功能没有删除任何东西。 我需要到达父级并从数组中删除它。 树看起来像这样:
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()
}
答案 0 :(得分:1)
这不适合您,因为_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))