Last active
February 21, 2023 21:30
-
-
Save jellybeansoup/60f6fe40d19c3c82cce02f14a5aac9fc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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