-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSampleValue.swift
More file actions
100 lines (76 loc) · 2.73 KB
/
SampleValue.swift
File metadata and controls
100 lines (76 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//
// SampleValue.swift
//
// Created by Nathan Racklyeft on 1/24/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
public protocol TimelineValue {
var startDate: Date { get }
var endDate: Date { get }
}
public extension TimelineValue {
var endDate: Date {
return startDate
}
}
public protocol SampleValue: TimelineValue {
var quantity: LoopQuantity { get }
}
public extension Sequence where Element: TimelineValue {
/**
Returns the closest element in the sorted sequence prior to the specified date
- parameter date: The date to use in the search
- returns: The closest index, if any exist before the specified date
*/
func closestPrior(to date: Date) -> Iterator.Element? {
return elementsAdjacent(to: date).before
}
/// Returns the elements immediately before and after the specified date
///
/// - Parameter date: The date to use in the search
/// - Returns: The closest elements, if found
func elementsAdjacent(to date: Date) -> (before: Iterator.Element?, after: Iterator.Element?) {
var before: Iterator.Element?
var after: Iterator.Element?
for value in self {
if value.startDate <= date {
before = value
} else {
after = value
break
}
}
return (before, after)
}
/**
Returns an array of elements filtered by the specified date range.
This behavior mimics HKQueryOptionNone, where the value must merely overlap the specified range,
not strictly exist inside of it.
- parameter startDate: The earliest date of elements to return
- parameter endDate: The latest date of elements to return
- returns: A new array of elements
*/
func filterDateRange(_ startDate: Date?, _ endDate: Date?) -> [Iterator.Element] {
return filter { (value) -> Bool in
if let startDate = startDate, value.endDate < startDate {
return false
}
if let endDate = endDate, value.startDate > endDate {
return false
}
return true
}
}
/**
Returns an array of elements filtered by the specified DateInterval.
This behavior mimics HKQueryOptionNone, where the value must merely overlap the specified range,
not strictly exist inside of it.
- parameter startDate: The earliest date of elements to return
- parameter endDate: The latest date of elements to return
- returns: A new array of elements
*/
func filterDateInterval(interval: DateInterval) -> [Iterator.Element] {
return filterDateRange(interval.start, interval.end)
}
}