-
Notifications
You must be signed in to change notification settings - Fork 0
/
lock-fsm.js
93 lines (74 loc) · 1.66 KB
/
lock-fsm.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
class LockFSM {
constructor() {
console.log('Lock Finite State Machine');
}
state = null;
key = () => {
this.state.key(this);
};
enter = () => {
this.state.enter(this);
};
_unlock = () => {
console.log('Door Unlocked, You can go inside the home');
};
_lock = () => {
console.log('Door Locked after getting inside the home');
};
_triggerAlarm = () => {
console.log('Warning: You can\'t enter the locked door !!!. Give key');
};
_sayItIsOpen = () => {
console.log('Door is open already');
};
}
const lockedState = {
key: fsm => {
fsm._unlock();
fsm.state = unlockedState;
},
enter: fsm => {
fsm._triggerAlarm();
fsm.state = lockedState;
},
};
const unlockedState = {
key: fsm => {
fsm._sayItIsOpen();
fsm.state = unlockedState;
},
enter: fsm => {
fsm._lock();
fsm.state = lockedState;
},
};
const enableLock = fsm => {
console.log('Lock System On');
fsm.state = lockedState;
};
const disableLock = fsm => {
console.log('Lock System Off');
fsm.state = null;
};
const doorLock = new LockFSM();
//Lock Finite State Machine
enableLock(doorLock);
//Lock System On
doorLock.key();
//Door Unlocked, You can go inside the home
doorLock.key();
//Door is open already
doorLock.enter();
//Door Locked after getting inside the home
doorLock.enter();
//Warning: You can't enter the locked door !!!. Give key
doorLock.enter();
//Warning: You can't enter the locked door !!!. Give key
doorLock.key();
//Door Unlocked, You can go inside the home
doorLock.key();
//Door is open already
doorLock.enter();
//Door Locked after getting inside the home
disableLock(doorLock);
//Lock System Off