Skip to content

Commit

Permalink
Refactor updateOrGiveup functions
Browse files Browse the repository at this point in the history
Faster and better
  • Loading branch information
lenguyenthanh committed Feb 26, 2024
1 parent a27d601 commit 69ca0ea
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
15 changes: 5 additions & 10 deletions app/src/main/scala/AppState.scala
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ object AppState:
)
))
case _ =>
val (newState, failedMove) = state.updateOrGiveUp(work.invalid)
newState -> (Logger[IO].warn(s"Give up move: $failedMove") >>
val newState = work.shouldGiveUp.fold(state)(state.updated(work.id, _))
newState -> (Logger[IO].warn(s"Give up move: $work") >>
monitor.failure(work, apikey, new Exception("Missing move")))
case Some(move) =>
state -> monitor.notAcquired(move, apikey)
Expand All @@ -55,11 +55,6 @@ object AppState:
state.values.filter(_.nonAcquired).minByOption(_.createdAt)

def updateOrGiveUp(candidates: List[Work.Move]): (AppState, List[Work.Move]) =
candidates.foldLeft[(AppState, List[Work.Move])](state -> Nil): (x, m) =>
val (newState, move) = x._1.updateOrGiveUp(m.timeout)
newState -> move.fold(x._2)(_ :: x._2)

def updateOrGiveUp(move: Work.Move): (AppState, Option[Work.Move]) =
val newState = state - move.id
if move.isOutOfTries then (newState, move.some)
else newState.updated(move.id, move) -> none
val gaveUps = candidates.foldLeft[List[Work.Move]](Nil): (xs, m) =>
m.shouldGiveUp.fold(xs)(_ :: xs)
state -- gaveUps.map(_.id) -> gaveUps
5 changes: 4 additions & 1 deletion app/src/main/scala/Work.scala
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,13 @@ object Work:
def timeout = copy(acquired = None)
def invalid = copy(acquired = None)

def isOutOfTries = tries >= 3
def isOutOfTries = tries >= 2

def similar(to: Move) = request.id == to.request.id && request.moves == to.request.moves

def shouldGiveUp: Option[Work.Move] =
Option.when(isOutOfTries)(timeout)

override def toString =
s"id:$id game:${request.id} variant:${request.variant.key} level:${request.level} tries:$tries created:$createdAt acquired:$acquired move: ${request.moves}"

Expand Down

0 comments on commit 69ca0ea

Please sign in to comment.