From e63c083a38b99da11c1c5e6d58a198ac2935dcfd Mon Sep 17 00:00:00 2001 From: Mark Schwerzler Date: Sun, 18 Aug 2024 19:37:29 -0400 Subject: [PATCH] Adding the handling of the random except last assigned assign state. --- internal/chore/handler.go | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/internal/chore/handler.go b/internal/chore/handler.go index 01490cc..69c7c31 100644 --- a/internal/chore/handler.go +++ b/internal/chore/handler.go @@ -1134,7 +1134,13 @@ func checkNextAssignee(chore *chModel.Chore, choresHistory []*chModel.ChoreHisto nextAssignee = chore.Assignees[rand.Intn(len(chore.Assignees))].UserID case "keep_last_assigned": // keep the last assignee - nextAssignee = history[len(history)-1].AssignedTo + nextAssignee = chore.AssignedTo + case "random_except_last_assigned": + var lastAssigned = chore.AssignedTo + AssigneesCopy := make([]chModel.ChoreAssignees, len(chore.Assignees)) + copy(AssigneesCopy, chore.Assignees) + var removeLastAssigned = remove(AssigneesCopy, lastAssigned) + nextAssignee = removeLastAssigned[rand.Intn(len(removeLastAssigned))].UserID default: return chore.AssignedTo, fmt.Errorf("invalid assign strategy") @@ -1143,6 +1149,25 @@ func checkNextAssignee(chore *chModel.Chore, choresHistory []*chModel.ChoreHisto return nextAssignee, nil } +func remove(s []chModel.ChoreAssignees, i int) []chModel.ChoreAssignees { + var removalIndex = indexOf(s, i) + if removalIndex == -1 { + return s + } + + s[removalIndex] = s[len(s)-1] + return s[:len(s)-1] +} + +func indexOf(arr []chModel.ChoreAssignees, value int) int { + for i, v := range arr { + if v.UserID == value { + return i + } + } + return -1 // Return -1 if the value is not found +} + func Routes(router *gin.Engine, h *Handler, auth *jwt.GinJWTMiddleware) { choresRoutes := router.Group("chores")