Skip to content

Instantly share code, notes, and snippets.

@asmallteapot
Created June 18, 2017 16:28
Show Gist options
  • Save asmallteapot/bcbb356222e46cd35208fcf484339b11 to your computer and use it in GitHub Desktop.
Save asmallteapot/bcbb356222e46cd35208fcf484339b11 to your computer and use it in GitHub Desktop.
Code koan: Dividing a `DateInterval` into sub-intervals by `Calendar.Component`s in Swift 4
extension Calendar {
func divide(interval dividend: DateInterval, by component: Calendar.Component, value divisor: Int) -> [DateInterval]? {
var intervals: [DateInterval] = []
var previousDate = dividend.start
while
let nextDate = self.date(byAdding: component, value: divisor, to: previousDate),
dividend.contains(nextDate)
{
let interval = DateInterval(start: previousDate, end: nextDate)
intervals.append(interval)
previousDate = nextDate
}
return intervals
}
}
@asmallteapot
Copy link
Author

The initial implementation ignores the remainder for DateIntervals that cannot be evenly divided.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment