Skip to content

Instantly share code, notes, and snippets.

@serhiybutz
Created September 27, 2021 23:03
Show Gist options
  • Save serhiybutz/bffaa0746286020e1191062abd32f869 to your computer and use it in GitHub Desktop.
Save serhiybutz/bffaa0746286020e1191062abd32f869 to your computer and use it in GitHub Desktop.
/// Traffic consumer account.
final class TrafficAccount {
// MARK: - Properties (State)
private var balance: Double = 0 // remaining money
private var traffic: Double = 0 // traffic consumed
// MARK: - Queries
public var currentBalance: Double { balance }
public var currentTraffic: Double { traffic }
public var summary: (balance: Double, traffic: Double) { (balance: balance, traffic: traffic) }
// MARK: - Commands
public func topUp(for amount: Double) {
balance += amount
}
public func consume(_ gb: Double, at costPerGb: Double) -> Double {
let cost = gb * costPerGb
let spent = balance < cost ? balance : cost
balance -= spent
let consumed = spent / costPerGb
traffic += consumed
return consumed
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment