-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfa.js
59 lines (46 loc) · 1.34 KB
/
dfa.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
/** Deterministic Finite Automaton */
class DFA {
constructor(rules, init, ...accept) {
this.rules = rules
this.init = init
this.state = init
this.accept = accept
}
compute(input) {
this.state = this.init
for (let i = 0; i < input.length; i++) {
const symbol = input[i]
if (!this.next(symbol)) return 'rejected'
}
return this.accept.includes(this.state)
? 'accepted' : 'rejected'
}
next(symbol) {
const rule = this.rules.find(r =>
r.state === this.state &&
r.symbol === symbol)
if (!rule) return false
this.state = rule.next
if (rule.action) rule.action()
return true
}
}
class Rule {
constructor(state, symbol, next, action) {
this.state = state
this.symbol = symbol
this.next = next
this.action = action
}
}
const Rs = new DFA([
new Rule('S', 'R', 'OK'),
new Rule('OK', 'R', 'OK')
], 'S', 'OK'
)
console.log(Rs.compute('')) // rejected
console.log(Rs.compute('r')) // rejected
console.log(Rs.compute('R')) // accepted
console.log(Rs.compute('Rr')) // rejected
console.log(Rs.compute('RRRRR')) // accepted
console.log(Rs.compute('RRRRRr')) // rejected