Skip to content

Commit

Permalink
feat: add Service class to provide additional functionalities
Browse files Browse the repository at this point in the history
  • Loading branch information
triplem committed Dec 24, 2024
1 parent e7cac05 commit f922941
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/main/kotlin/org/javafreedom/khol/KHolServices.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package org.javafreedom.khol

import kotlinx.datetime.DayOfWeek
import kotlinx.datetime.LocalDate
import org.javafreedom.khol.helper.rangeTo

/**
* Provide some useful Service functions
*/
class KHolServices {

fun workdays(holidays: List<LocalDate>,
start: LocalDate, end: LocalDate): List<LocalDate> =
(start..end)
.filter { isHoliday(holidays, it) }
.filter { !isWeekend(it) }
.toList()

fun isHoliday(holidays: List<LocalDate>, date: LocalDate) = holidays.contains(date)

fun isWeekend(date: LocalDate) =
date.dayOfWeek == DayOfWeek.SATURDAY || date.dayOfWeek == DayOfWeek.SUNDAY
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package org.javafreedom.khol.helper

import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.plus

/**
* This provides the iterator to be used in the progression. This can then used in range queries.
*
* Cloned by https://www.netguru.com/blog/traversing-through-dates-with-kotlin-range-expressions
*/
class DateIterator(val startDate: LocalDate,
val endDateExclusive: LocalDate,
val stepDays: Long): Iterator<LocalDate> {
private var currentDate = startDate

override fun hasNext() = currentDate < endDateExclusive

override fun next(): LocalDate {
val next = currentDate
currentDate = currentDate.plus(stepDays, DateTimeUnit.DAY)
return next
}

}

/**
* The progression used to loop through a range of localDates
*/
class DateProgression(override val start: LocalDate,
override val endInclusive: LocalDate,
val stepDays: Long = 1) :
Iterable<LocalDate>, ClosedRange<LocalDate> {

override fun iterator(): Iterator<LocalDate> =
DateIterator(start, endInclusive, stepDays)

infix fun step(days: Long) = DateProgression(start, endInclusive, days)
}

/**
* Extension Function to make the localdate range work
*/
operator fun LocalDate.rangeTo(other: LocalDate) = DateProgression(this, other)

0 comments on commit f922941

Please sign in to comment.