-
Notifications
You must be signed in to change notification settings - Fork 4
/
UtilityAi.js
99 lines (76 loc) · 1.97 KB
/
UtilityAi.js
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
class Action {
constructor(description, callback) {
this.description = description
this._scores = []
this._condition = () => true
callback(this)
}
condition(callback) {
if (!callback) {
throw Error("UtilityAi#Action#condition: Missing callback")
}
this._condition = callback
}
score(description, callback) {
if (!description) {
throw Error("UtilityAi#Action#score: Missing description")
}
if (!callback) {
throw Error("UtilityAi#Action#score: Missing callback")
}
this._scores.push({
description,
callback
})
}
_validateScore(score) {
if (!isNaN(score) && typeof score === "number") {
return score
}
return 0
}
log(...msg) {
if (!this._print_debug) return
console.log(...msg)
}
evaluate(data, debug = false) {
this._print_debug = debug
this.log("Evaluate Action: ", this.description)
if (!this._condition(data)) {
this.log("Condition not fulfilled")
return -Infinity
}
const score = this._scores
.map(score => {
const _score = this._validateScore(score.callback(data))
this.log("- ", score.description, _score)
return _score
})
.reduce((acc, score) => acc + score, 0)
this.log("Final Score: ", score)
return score
}
}
module.exports = class UtilityAi {
constructor() {
this._actions = []
}
addAction(description, callback) {
if (!description) {
throw Error("UtilityAi#addAction: Missing description")
}
if (!callback) {
throw Error("UtilityAi#addAction: Missing callback")
}
const action = new Action(description, callback)
this._actions.push(action)
}
evaluate(data, debug = false) {
return this._actions
.map(action => ({
action: action.description,
score: action.evaluate(data, debug)
}))
.reduce((acc, action) => acc.score !== undefined && acc.score > action.score ? acc : action, {})
}
}