cshenfu
2023-05-08 2469d92f4c189eb595216707f4b4f0786fadb23f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
'use strict';
 
class Command {
 
  constructor() {
    this._registered = {}
  }
 
  async execute(name, args) {
    if (this._registered[name]) {
      return await this._registered[name].execute(args)
    }
  }
 
  canExecute(name, args) {
    if (this._registered[name] && this._registered[name].canExecute) {
      this._registered[name].canExecute(args)
    }
    return false
  }
 
  register(name, execute, canExecute) {
    this._registered[name] = {
      execute,
      canExecute
    }
  }
}
 
class Task {
 
  constructor(id) {
    this._id = id || this._newTaskId()
 
    this._state = Task.TASK_STATE.WAITING
  }
 
  async run() {}
 
  async cancel() {}
 
  async taskAction() {}
 
  _newTaskId() {
    let guid = ''
    const format = 'xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx'
    for (let i = 0; i < format.length; i++) {
      if (format[i] === 'x') {
        guid += (Math.random() * 16 | 0).toString(16)
      } else {
        guid += format[i]
      }
    }
    return guid.toUpperCase()
  }
 
  get id() {
    return this._id
  }
  set id(value) {
    this._id = value
  }
 
  get state() {
    return this._state
  }
  set state(value) {
    this._state = value
  }
}
 
Task.TASK_STATE = {
  WAITING: "WAITING",
  RESOLVING: "RESOLVING",
  RESOLVED: "RESOLVED",
  EXECUTING: "EXECUTING",
  ERROR: "ERROR",
  COMPLETED: "COMPLETED",
  CANCELLING: "CANCELLING",
  CANCELLED: "CANCELLED"
}
 
class TaskManager {
 
  constructor() {
    this._tasks = []
  }
 
  get tasks() {
    return this._tasks
  }
 
  clear() {
    this._tasks.length = 0
  }
 
  getTask(id) {
    return this._tasks.find((item) => {
      return (item.id == id)
    })
  }
 
  addTask(task) {
    this._tasks.push(task)
  }
 
  deleteTask(id) {
    const index = this.findIndex(id)
    if (index < 0) {
      return
    }
 
    this._tasks[index].cancel()
 
    if (index > -1) {
      this._tasks.splice(index, 1)
    }
  }
 
  findIndex(id) {
    return this._tasks.findIndex((item) => {
      return (item.id == id)
    })
  }
}
 
module.exports = {
  Command,
  Task,
  TaskManager
};