Math.swift 680 B

12345678910111213141516171819202122232425
  1. //
  2. // Math.swift
  3. // LoopKitUI
  4. //
  5. // Created by Michael Pangburn on 3/23/19.
  6. // Copyright © 2019 LoopKit Authors. All rights reserved.
  7. //
  8. func fractionThrough<Metric: FloatingPoint>(
  9. _ value: Metric,
  10. in range: ClosedRange<Metric>,
  11. using transform: (Metric) -> Metric = { $0 }
  12. ) -> Metric {
  13. let transformedLowerBound = transform(range.lowerBound)
  14. return (transform(value) - transformedLowerBound) / (transform(range.upperBound) - transformedLowerBound)
  15. }
  16. func interpolatedValue<Metric: FloatingPoint>(
  17. at fraction: Metric,
  18. through range: ClosedRange<Metric>
  19. ) -> Metric {
  20. fraction * (range.upperBound - range.lowerBound) + range.lowerBound
  21. }