Created
September 27, 2021 23:06
-
-
Save serhiybutz/e650dce7010aa0e52e5fc4d99e19ab29 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
/// Traffic consumer account. | |
struct TrafficAccount { | |
// MARK: - Properties (State) | |
private let balance = Property<Double>(value: 0) // remaining money | |
private let traffic = Property<Double>(value: 0) // traffic consumed | |
private let sharedManager = SharedManager() | |
// MARK: - Queries | |
public var currentBalance: Double { | |
sharedManager.borrow(balance) { $0.value } | |
} | |
public var currentTraffic: Double { | |
sharedManager.borrow(traffic) { $0.value } | |
} | |
public var summary: (balance: Double, traffic: Double) { | |
sharedManager.borrow(balance, traffic) { (balance: $0.value, traffic: $1.value) } | |
} | |
// MARK: - Commands | |
public func topUp(for amount: Double) { | |
sharedManager.borrow(balance) { $0.value += amount } | |
} | |
public func consume(_ gb: Double, at costPerGb: Double) -> Double { | |
sharedManager.borrow(balance, traffic) { balance, traffic in | |
let cost = gb * costPerGb | |
let spent = balance.value < cost ? balance.value : cost | |
balance.value -= spent | |
let consumed = spent / costPerGb | |
traffic.value += consumed | |
return consumed | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment