Skip to content
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
21 changes: 13 additions & 8 deletions core/src/main/scala/HasId.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,21 @@ trait HasId[A, Id]:
inline def hasId(id: Id): Boolean = a.id == id

extension (xs: List[A])
def remove(v: A): List[A] =
final def remove(v: A): List[A] =
xs.removeById(v.id)

def removeById(id: Id): List[A] =
xs.foldLeft((false, List.empty[A])) { (acc, v) =>
if acc._1 then (acc._1, v :: acc._2)
else if v.hasId(id) then (true, acc._2)
else (false, v :: acc._2)
}._2
.reverse
// Remove first item with the given id
// if there is no match return the original list
// This behavior is to accomodate the lila study tree current implementation
// We should change it after We finally migrate it to this new tree
final def removeById(id: Id): List[A] =
@tailrec
def loop(acc: List[A], rest: List[A]): List[A] =
rest match
case (v :: vs) if v.hasId(id) => acc ++ vs
case (v :: vs) => loop(acc :+ v, vs)
case Nil => acc
loop(Nil, xs)

trait Mergeable[A]:

Expand Down
17 changes: 13 additions & 4 deletions test-kit/src/test/scala/HasIdTest.scala
Original file line number Diff line number Diff line change
@@ -1,20 +1,29 @@
package chess

import munit.ScalaCheckSuite
import org.scalacheck.Prop.forAll
import org.scalacheck.Prop.{ forAll, propBoolean }

class HasIdTest extends ScalaCheckSuite:

given HasId[Int, Int] with
extension (a: Int) def id: Int = a

test("removeById.size <= size"):
test("if there is no id, removeById does nothing"):
forAll: (xs: List[Int], id: Int) =>
val removed = xs.removeById(id)
xs.size == removed.size || xs.size == removed.size + 1
xs.indexOf(id) == -1 ==> (xs.removeById(id) == xs)

test("removeById.size <= size"):
forAll: (xs: List[Int], id: Int) =>
val removed = xs.removeById(id)
val epsilon = if xs.find(_ == id).isDefined then 1 else 0
xs.size == removed.size + epsilon

test("removeById reserves order"):
forAll: (xs: List[Int], id: Int) =>
val sorted = xs.sorted
val removed = sorted.removeById(id)
removed == removed.sorted

test("removeById only remove first items"):
val xs = List(1, 2, 1)
xs.removeById(1) == List(2, 1)