Refactor scheduleAdaptiveNextDueDate function for improved readability and fix bug, Add New Tests for it

This commit is contained in:
Mo Tarbin 2024-08-10 00:27:07 -04:00
parent 042cd3b473
commit 4f22460313
3 changed files with 251 additions and 12 deletions

View file

@ -3,6 +3,7 @@ package chore
import (
"encoding/json"
"fmt"
"math"
"math/rand"
"strings"
"time"
@ -141,11 +142,15 @@ func scheduleNextDueDate(chore *chModel.Chore, completedDate time.Time) (*time.T
return &nextDueDate, nil
}
func scheduleAdaptiveNextDueDate(chore *chModel.Chore, completedDate time.Time, history []*chModel.ChoreHistory) (*time.Time, error) {
// will generate due date base on history and the different between the completed date and the due date
// the more recent the higher weight
if len(history) <= 1 {
history = append([]*chModel.ChoreHistory{
{
CompletedAt: &completedDate,
},
}, history...)
if len(history) < 2 {
if chore.NextDueDate != nil {
diff := completedDate.UTC().Sub(chore.NextDueDate.UTC())
nextDueDate := completedDate.UTC().Add(diff)
@ -153,22 +158,23 @@ func scheduleAdaptiveNextDueDate(chore *chModel.Chore, completedDate time.Time,
}
return nil, nil
}
var weight float64
var totalDelay float64
var totalWeight float64
var nextDueDate time.Time
decayFactor := 0.5 // Adjust this value to control the decay rate
for i := 0; i < len(history)-1; i++ {
delay := history[i].CompletedAt.UTC().Sub(history[i+1].CompletedAt.UTC()).Seconds()
weight = delay * float64(len(history)-i)
weight := math.Pow(decayFactor, float64(i))
totalDelay += delay * weight
totalWeight += weight
}
// calculate the average delay
averageDelay := totalWeight / float64(len(history)-1)
// calculate the difference between the completed date and the due date
nextDueDate = completedDate.UTC().Add(time.Duration(averageDelay) * time.Second)
averageDelay := totalDelay / totalWeight
nextDueDate := completedDate.UTC().Add(time.Duration(averageDelay) * time.Second)
return &nextDueDate, nil
}
func RemoveAssigneeAndReassign(chore *chModel.Chore, userID int) {
for i, assignee := range chore.Assignees {
if assignee.UserID == userID {