ComputedInsulinSensitivities+Getter.swift 950 B

12345678910111213141516171819202122232425
  1. import Foundation
  2. extension ComputedInsulinSensitivities {
  3. /// Returns the insulin sensitivity (ISF) for a specific Date (using the closest entry).
  4. func sensitivity(for date: Date) -> Decimal? {
  5. guard !sensitivities.isEmpty else { return nil }
  6. // Assumes all offsets are in minutes from midnight
  7. let calendar = Calendar.current
  8. let components = calendar.dateComponents([.hour, .minute], from: date)
  9. let minutesSinceMidnight = (components.hour ?? 0) * 60 + (components.minute ?? 0)
  10. // Find the entry whose offset is the largest but not greater than the time
  11. let sorted = sensitivities.sorted(by: { $0.offset < $1.offset })
  12. var current = sorted.first
  13. for entry in sorted {
  14. if entry.offset <= minutesSinceMidnight {
  15. current = entry
  16. } else {
  17. break
  18. }
  19. }
  20. return current?.sensitivity
  21. }
  22. }