35 lines
1.6 KiB
Swift
35 lines
1.6 KiB
Swift
import Foundation
|
|
|
|
nonisolated enum PanelCurveGeometry {
|
|
struct Sample {
|
|
let date: Date
|
|
let value: Double
|
|
var lower: Double = 0
|
|
}
|
|
|
|
static func allowedGap(at index: Int, intervals: [TimeInterval], fallback: TimeInterval) -> TimeInterval {
|
|
guard index > 0, index < intervals.count else { return fallback }
|
|
let interval = intervals[index - 1]
|
|
return interval.isFinite && interval > 0 ? max(5, interval * 2) : fallback
|
|
}
|
|
|
|
static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set<Date> = [], intervals: [TimeInterval] = [], lowerValues: [Double?]? = nil) -> [[Sample]] {
|
|
var result: [[Sample]] = []
|
|
var run: [Sample] = []
|
|
func flush() { if !run.isEmpty { result.append(run); run.removeAll(keepingCapacity: true) } }
|
|
for index in dates.indices {
|
|
if index > 0 && (boundaryDates.contains(dates[index]) || dates[index].timeIntervalSince(dates[index - 1]) > allowedGap(at: index, intervals: intervals, fallback: maximumGap) || dates[index] <= dates[index - 1]) { flush() }
|
|
// Missing values do not create vertices, but their timestamps can still carry a real break.
|
|
guard index < values.count, let value = values[index], value.isFinite else { continue }
|
|
var lower = 0.0
|
|
if let lowerValues {
|
|
guard lowerValues.indices.contains(index), let base = lowerValues[index], base.isFinite else { continue }
|
|
lower = base
|
|
}
|
|
run.append(Sample(date: dates[index], value: value, lower: lower))
|
|
}
|
|
flush()
|
|
return result
|
|
}
|
|
}
|