Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix wrong implementation of decrementing and incrementing months #67

Merged
merged 1 commit into from
May 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package io.github.boguszpawlowski.composecalendar.kotlinxDateTime
import kotlinx.datetime.DateTimeUnit
import kotlinx.datetime.LocalDate
import kotlinx.datetime.Month
import java.time.Month.DECEMBER
import java.time.Month.JANUARY
import java.time.temporal.ChronoField.YEAR

/**
Expand All @@ -22,18 +20,12 @@ public data class YearMonth private constructor(
/**
* Increment by one month
*/
public operator fun inc(): YearMonth = when (month.value) {
in 1..11 -> YearMonth(year, month)
else -> YearMonth(year + 1, JANUARY)
}
public operator fun inc(): YearMonth = plus(1, DateTimeUnit.MONTH)

/**
* Decrement by one month
*/
public operator fun dec(): YearMonth = when (month.value) {
in 2..12 -> YearMonth(year, month)
else -> YearMonth(year - 1, DECEMBER)
}
public operator fun dec(): YearMonth = minus(1, DateTimeUnit.MONTH)

/**
* Add specified amount of months to current date
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,5 +88,41 @@ internal class YearMonthTest : ShouldSpec({
result shouldBe expectedYear
}
}
context("when decrementing") {
should("subtract one month") {
val yearMonth = YearMonth.of(2002, 11)
val expectedResult = YearMonth.of(2002, 10)

val result = yearMonth.dec()

result shouldBe expectedResult
}
should("overflow the year when january") {
val yearMonth = YearMonth.of(2002, 1)
val expectedResult = YearMonth.of(2001, 12)

val result = yearMonth.dec()

result shouldBe expectedResult
}
}
context("when incrementing") {
should("add one month") {
val yearMonth = YearMonth.of(2002, 11)
val expectedResult = YearMonth.of(2002, 12)

val result = yearMonth.inc()

result shouldBe expectedResult
}
should("overflow the year when december") {
val yearMonth = YearMonth.of(2002, 12)
val expectedResult = YearMonth.of(2003, 1)

val result = yearMonth.inc()

result shouldBe expectedResult
}
}
}
})