shyiko / skedule

A human-friendly alternative to cron. Designed after GAE's schedule for Kotlin and/or Java 8+.
84 stars 7 forks source link

Iterable starting from "same" #8

Open rocketraman opened 3 years ago

rocketraman commented 3 years ago

It would be nice if it was possible to call a variation of the iterate method that starts at the "same" instant as the timestamp.

Since I am using Kotlin, and want a Sequence rather than an Iterator I am working around this with the following extensions:

/**
 * Similar to `asSequence` on [ScheduleIterator] but calls `nextOrSame` instead of `next` to obtain the
 * first element.
 */
fun <T> Schedule.ScheduleIterator<T>.asSequenceStartingFromNextOrSame(): Sequence<T> = generateSequence({ nextOrSame() }) {
  next()
}

fun Schedule.asSequence(timestamp: ZonedDateTime, startingFromSame: Boolean = false): Sequence<ZonedDateTime> {
  val scheduleIterator = iterate(timestamp)
  return if(startingFromSame) scheduleIterator.asSequenceStartingFromNextOrSame() else scheduleIterator.asSequence()
}