-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInterpreter-Pattern.js
More file actions
53 lines (45 loc) · 1.18 KB
/
Copy pathInterpreter-Pattern.js
File metadata and controls
53 lines (45 loc) · 1.18 KB
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
// 解释器模式(Interpreter Pattern)
// 基础表达式:判断是否包含关键词
class Keyword {
constructor(word) {
this.word = word
}
interpret(context) {
return context.includes(this.word)
}
}
// 或表达式:满足任意一个条件
class Or {
constructor(left, right) {
this.left = left
this.right = right
}
interpret(context) {
return this.left.interpret(context) ||
this.right.interpret(context)
}
}
// 与表达式:必须同时满足两个条件
class And {
constructor(left, right) {
this.left = left
this.right = right
}
interpret(context) {
return this.left.interpret(context) &&
this.right.interpret(context)
}
}
// 构建规则:(John OR Robert) AND Married
const rule = new And(
new Or(
new Keyword('John'),
new Keyword('Robert')
),
new Keyword('Married')
)
// 解释输入,得到结果
console.log(rule.interpret('John Married')) // true
console.log(rule.interpret('Robert Married')) // true
console.log(rule.interpret('John')) // false
console.log(rule.interpret('Julie Married')) // false