@j0u1/finity 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.test.ts +19 -1
- package/index.ts +8 -1
- package/package.json +1 -1
package/index.test.ts
CHANGED
|
@@ -1,9 +1,27 @@
|
|
|
1
1
|
import { test, expect } from "bun:test"
|
|
2
2
|
import { createMachine } from "./index"
|
|
3
3
|
|
|
4
|
-
test("
|
|
4
|
+
test("initial state", () => {
|
|
5
5
|
const m = createMachine({ initial: 'red', transitions: { red: 'yellow' } })
|
|
6
6
|
expect(m.current).toBe('red')
|
|
7
|
+
})
|
|
8
|
+
|
|
9
|
+
test("next() changes state", () => {
|
|
10
|
+
const m = createMachine({ initial: 'red', transitions: { red: 'yellow' } })
|
|
7
11
|
expect(m.next()).toBe('yellow')
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
test("can() returns true if transition is possible", () => {
|
|
15
|
+
const m = createMachine({ initial: 'red', transitions: { red: 'yellow' } })
|
|
16
|
+
expect(m.can('yellow')).toBe(true)
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
test("can() returns false if transition is not possible", () => {
|
|
20
|
+
const m = createMachine({ initial: 'red', transitions: { red: 'yellow' } })
|
|
8
21
|
expect(m.can('green')).toBe(false)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
test("next() throws if no transition exists", () => {
|
|
25
|
+
const m = createMachine({ initial: 'red', transitions: {} })
|
|
26
|
+
expect(() => m.next()).toThrow('No transition from "red"')
|
|
9
27
|
})
|
package/index.ts
CHANGED
|
@@ -3,6 +3,13 @@ interface ConfigType {
|
|
|
3
3
|
transitions: Record<string, string>
|
|
4
4
|
}
|
|
5
5
|
|
|
6
|
+
class FinityError extends Error {
|
|
7
|
+
constructor(message: string) {
|
|
8
|
+
super(message)
|
|
9
|
+
this.name = 'FinityError'
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
6
13
|
export function createMachine(config: ConfigType) {
|
|
7
14
|
return {
|
|
8
15
|
current: config.initial,
|
|
@@ -10,7 +17,7 @@ export function createMachine(config: ConfigType) {
|
|
|
10
17
|
|
|
11
18
|
next() {
|
|
12
19
|
const nextState = this.transitions[this.current]
|
|
13
|
-
if (!nextState) throw new
|
|
20
|
+
if (!nextState) throw new FinityError(`No transition from "${this.current}"`)
|
|
14
21
|
return this.current = nextState
|
|
15
22
|
},
|
|
16
23
|
can(state: string) {
|