Skip to content

Commit

Permalink
Make sure there are no gaps in index
Browse files Browse the repository at this point in the history
This is used to define multiplicity which must start at 0 and
have no gaps
  • Loading branch information
seadowg committed Jul 12, 2024
1 parent 8d4a4bd commit c37abf5
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,15 @@ class JsonFileEntitiesRepository(directory: File) : EntitiesRepository {
override fun delete(id: String) {
val existing = readEntities()
existing.removeIf { it.id == id }
writeEntities(existing)

val withAdjustedIndex = existing.mapIndexed { index, entity ->
entity.copy(index = index)
}

writeEntities(withAdjustedIndex)
}

private fun writeEntities(entities: MutableList<Entity.Saved>) {
private fun writeEntities(entities: List<Entity.Saved>) {
val map = mutableMapOf<String, MutableList<JsonEntity>>()
entities.forEach {
map.getOrPut(it.list) { mutableListOf() }.add(it.toJson())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,15 +287,24 @@ abstract class EntitiesRepositoryTest {
}

@Test
fun `#delete does not change index values for remaining entities`() {
fun `#delete updates index values so that they are always in sequence and start at 0`() {
val repository = buildSubject()

val leoville = Entity.New("wines", "1", "Léoville Barton 2008")
val canet = Entity.New("wines", "2", "Pontet-Canet 2014")
repository.save(leoville, canet)
val gloria = Entity.New("wines", "3", "Chateau Gloria 2016")
repository.save(leoville, canet, gloria)

repository.delete("1")

assertThat(repository.getEntities("wines")[0].index, equalTo(1))
var wines = repository.getEntities("wines")
assertThat(wines[0].index, equalTo(0))
assertThat(wines[1].index, equalTo(1))

repository.save(leoville)
wines = repository.getEntities("wines")
assertThat(wines[0].index, equalTo(0))
assertThat(wines[1].index, equalTo(1))
assertThat(wines[2].index, equalTo(2))
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package org.odk.collect.entities.storage

class InMemEntitiesRepository(private val startingIndex: Int = 0) : EntitiesRepository {
class InMemEntitiesRepository(startingIndex: Int = 0) : EntitiesRepository {

private val lists = mutableSetOf<String>()
private val entities = mutableListOf<Entity.Saved>()
Expand All @@ -26,6 +26,14 @@ class InMemEntitiesRepository(private val startingIndex: Int = 0) : EntitiesRepo

override fun delete(id: String) {
entities.removeIf { it.id == id }

indexCounter--
val withAdjustedIndex = entities.mapIndexed { index, entity ->
entity.copy(index = index)
}

entities.clear()
entities.addAll(withAdjustedIndex)
}

override fun save(vararg entities: Entity) {
Expand Down

0 comments on commit c37abf5

Please sign in to comment.