Skip to content

Instantly share code, notes, and snippets.

@jellybeansoup
Last active February 21, 2023 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jellybeansoup/60f6fe40d19c3c82cce02f14a5aac9fc to your computer and use it in GitHub Desktop.
Save jellybeansoup/60f6fe40d19c3c82cce02f14a5aac9fc to your computer and use it in GitHub Desktop.
import Foundation
actor SixSidedDie {
struct Environment: Sendable {
var doTheThing: @Sendable (_ range: ClosedRange<Int>) -> Int
}
private var environment = Environment(
doTheThing: { Int.random(in: $0) }
)
func updateEnvironment<T>(_ handler: (_ environment: inout Environment) -> T) -> T {
handler(&environment)
}
func roll() -> Int {
environment.doTheThing(1...6)
}
}
class SixSidedDieTests {
func testRanges() async {
let die = SixSidedDie()
let ranges = await die.updateEnvironment { environment in
return AsyncStream { continuation in
environment.doTheThing = { [original = environment.doTheThing] range in
continuation.yield(range)
return original(range)
}
}
}
await die.roll()
await die.roll()
await die.roll()
await print(ranges.allSatisfy { $0 == 1...6 })
}
}
Task {
await SixSidedDieTests().testRanges()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment