Skip to content

Commit 6c7ef54

Browse files
committed
Simple state machine
1 parent e24d105 commit 6c7ef54

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package nl.fifthpostulate.statemachine
2+
3+
import nl.fifthpostulate.FizzBuzz
4+
5+
sealed class State : FizzBuzz {
6+
lateinit var next: State
7+
}
8+
class FizzState : State() {
9+
override fun of(n: Int): String = "Fizz"
10+
}
11+
class BuzzState : State() {
12+
override fun of(n: Int): String = "Buzz"
13+
}
14+
class FizzBuzzState : State() {
15+
override fun of(n: Int): String = "FizzBuzz"
16+
}
17+
class NumberState : State() {
18+
override fun of(n: Int): String = n.toString()
19+
}
20+
21+
fun buildStates(): State {
22+
val l = listOf(
23+
FizzBuzzState(), NumberState(), NumberState(), FizzState(), NumberState(),
24+
BuzzState(), FizzState(), NumberState(), NumberState(), FizzState(),
25+
BuzzState(), NumberState(), FizzState(), NumberState(), NumberState(),
26+
)
27+
28+
var state = l.first()
29+
for (s in l.drop(1)) {
30+
state.next = s
31+
state = s
32+
}
33+
state.next = l.first()
34+
35+
return l.first()
36+
}
37+
38+
class StateMachine : FizzBuzz {
39+
private val start = buildStates()
40+
override fun of(n: Int): String {
41+
var state = start
42+
repeat(n) {
43+
state = state.next
44+
}
45+
return state.of(n)
46+
}
47+
}

src/test/kotlin/nl/fifthpostulate/FizzBuzzTest.kt

+2-1
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ import nl.fifthpostulate.radix.Radix
55
import nl.fifthpostulate.radix.UnrollWithMap
66
import nl.fifthpostulate.radix.UnrollWithWhen
77
import nl.fifthpostulate.standard.Standard
8+
import nl.fifthpostulate.statemachine.StateMachine
89
import org.junit.jupiter.api.BeforeEach
910
import kotlin.random.Random
10-
import kotlin.random.nextInt
1111
import kotlin.test.Test
1212
import kotlin.test.assertEquals
1313

@@ -23,6 +23,7 @@ class FizzBuzzTest {
2323
UnrollWithWhen(),
2424
UnrollWithMap(),
2525
CastingNines(),
26+
StateMachine(),
2627
)
2728
}
2829

0 commit comments

Comments
 (0)