Skip to content

Commit

Permalink
Fix the calculation of end ranges for averages
Browse files Browse the repository at this point in the history
  • Loading branch information
albertvaka committed Mar 2, 2024
1 parent 0b3cc92 commit f89e279
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,11 @@ fun Date.toCalendar(): Calendar {
cal.time = this
return cal
}

fun max(a: Date, b: Date): Date {
return if (a.time > b.time) a else b
}

fun min(a: Date, b: Date): Date {
return if (a.time < b.time) a else b
}
21 changes: 5 additions & 16 deletions app/src/main/java/org/kde/bettercounter/ui/ChartHolder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import androidx.recyclerview.widget.RecyclerView
import org.kde.bettercounter.R
import org.kde.bettercounter.databinding.FragmentChartBinding
import org.kde.bettercounter.extensions.count
import org.kde.bettercounter.extensions.max
import org.kde.bettercounter.extensions.min
import org.kde.bettercounter.persistence.CounterSummary
import org.kde.bettercounter.persistence.Entry
import org.kde.bettercounter.persistence.Interval
Expand Down Expand Up @@ -117,24 +119,11 @@ class ChartHolder(
rangeEnd.add(Calendar.MINUTE, -1)

val firstEntryDate = counter.leastRecent!!
val hasEntriesInPreviousPeriods = (firstEntryDate < rangeStart.time)
val startDate = if (hasEntriesInPreviousPeriods) {
// Use the period start as the start date
rangeStart.time
} else {
// Use the firstEntry as the start date
firstEntryDate
}

val lastEntryDate = counter.mostRecent!!
val now = Calendar.getInstance().time
val hasEntriesInFuturePeriods = (lastEntryDate > rangeEnd.time)
val hasEntriesInTheFuture = (lastEntryDate > now)
val endDate = when {
hasEntriesInFuturePeriods -> rangeEnd.time // Use the period end as the end date
hasEntriesInTheFuture -> lastEntryDate // Use lastEntry as the end date
else -> now // Use now as the end date
}

val startDate = max(rangeStart.time, min(firstEntryDate, now))
val endDate = min(rangeEnd.time, max(lastEntryDate, now))

return when (counter.interval) {
Interval.DAY -> getAverageStringPerHour(intervalEntries.size, startDate, endDate)
Expand Down

0 comments on commit f89e279

Please sign in to comment.