-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
30 lines (27 loc) · 862 Bytes
/
Copy pathindex.ts
File metadata and controls
30 lines (27 loc) · 862 Bytes
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
interface ConfigType {
initial: string,
transitions: Record<string, string | string[]>
}
class FinityError extends Error {
constructor(message: string) {
super(message)
this.name = 'FinityError'
}
}
export function createMachine(config: ConfigType) {
return {
current: config.initial,
transitions: config.transitions,
moveTo(state: string) {
const available = this.transitions[this.current]
const states = Array.isArray(available) ? available : [available]
if (!states.includes(state)) throw new FinityError(`No transition from "${this.current}" to "${state}"`)
return this.current = state
},
canChangeTo(state: string) {
const available = this.transitions[this.current]
const states = Array.isArray(available) ? available : [available]
return states.includes(state)
}
}
}