Home > other >  how to use recursion in javascript class?
how to use recursion in javascript class?

Time:11-30

class Tasks {
    constructor () {
        this.store = [];
    }

    addTask(taskName) {
        var task = {
        id:  Date.now(),
        task: taskName,
        children: []
            }
        this.store.push(task);
    }

    deleteTask(id) {
       this.store = this.store.filter(function(task) {return task.id! != 
       id});
    }
}

Currently I have this code. I access it by var todos = new Tasks(); adding todos.add('Do something'); todods.delete(id); This works for non nested tasks. I want to use this for nested tasks/todos.

I want to access the store in delete add methods so I can add or delete sub tasks recursively.

strore will look like this

nestedArr = [
    {
        id: 1,
        task: 'task 1',
        children[]
    },
    {
        id: 2,
        task: 'task 2',
        children [
            {
                id: 3,
                task: 'task 1',
                children[]
            },
            {
                id: 4,
                task: 'task 2',
                children [
                    {
                        id: 5,
                        task: 'task 1',
                        children[]
                    },
                    {
                        id: 6,
                        task: 'task 2',
                        children []
                    }
                ]
            }
        ]
    }
]

like I can do these using functions, but I want to use this in classes

deleteTask(arr, id) {      .....      
  this.deleteTask(arr.children, id) {          ... }
}

CodePudding user response:

I would instead structure the store like this, and have all tasks have "parent" as a property (-1 if they don't have a parent). The children array should contain the ids of it's children.

If you want to remove some items based on task, just do it in the following order:

  1. Loop through all items to find one or more matches.
  2. Remove all children for the tasks that are removed.
  3. If having a parent id, remove it from the children array if the parent still exist.
  4. Remove the task itself.

nestedArr = [{
    id: 1,
    task: 'task 1',
    parent: -1,
    children: []
  }, {
    id: 2,
    task: 'task 2',
    parent: -1,
    children: [3]
  }, {
    id: 3,
    task: 'task 1',
    parent: 2,
    children: []
  }, {
    id: 4,
    task: 'task 2',
    parent: -1,
    children: [5, 6]
  }, {
    id: 5,
    task: 'task 1',
    parent: 4,
    children: []
  }, {
    id: 6,
    task: 'task 2',
    parent: 4,
    children: []
  }
]

  • Related