import Foundation // Formatters.swift // Small, pure helpers: the maths and the text formatting for run numbers. // No Apple Health or screen code here, so these rules are easy to check. // (The web mockup uses exactly the same rules.) /// Calculations made from what Health recorded. Each one returns nil when the /// input is missing or too small to give a meaningful answer — we never guess. enum RunMath { /// Average pace in seconds per kilometre, e.g. 313.4 (= 5'13" per km). static func pace(seconds: TimeInterval, meters: Double?) -> Double? { guard let meters, meters >= 10, seconds > 0 else { return nil } return seconds / (meters / 1000) } /// Cadence (步频) in steps per minute: total steps ÷ minutes running. static func cadence(steps: Double?, seconds: TimeInterval) -> Double? { guard let steps, steps > 0, seconds >= 60 else { return nil } return steps / (seconds / 60) } } /// Turns numbers into the text shown on screen. enum RunFormat { /// 313.4 seconds per km -> 5'13" static func pace(_ secondsPerKm: Double) -> String { let total = Int(secondsPerKm.rounded()) let minutes = total / 60 let seconds = total % 60 return "\(minutes)'" + twoDigits(seconds) + "\"" } /// 3134 seconds -> 52:14, 3725 seconds -> 1:02:05 static func duration(_ seconds: TimeInterval) -> String { let total = Int(seconds.rounded()) let hours = total / 3600 let minutes = (total % 3600) / 60 let secs = total % 60 if hours > 0 { return "\(hours):" + twoDigits(minutes) + ":" + twoDigits(secs) } return "\(minutes):" + twoDigits(secs) } /// 10020 metres -> "10.02" (the screen adds the "km" label separately) static func kilometres(_ meters: Double) -> String { String(format: "%.2f", meters / 1000) } /// 151.6 -> "152" (heart rate, cadence, calories, metres of climb) static func whole(_ value: Double) -> String { String(Int(value.rounded())) } private static func twoDigits(_ value: Int) -> String { value < 10 ? "0\(value)" : "\(value)" } }