-
Notifications
You must be signed in to change notification settings - Fork 0
/
PersonRepository.kt
34 lines (26 loc) · 1 KB
/
PersonRepository.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
object PersonRepository {
var people: MutableList<Person> = mutableListOf()
fun clear() = people.clear()
fun addPerson(name: String): Person {
val id = nextId()
val person = Person(id, name, emptyList())
people.add(person)
return person
}
fun addPerson(person: Person) =
if (people.find { it.id == person.id } != null)
throw IllegalArgumentException("Already one person with that ID")
else
people.add(person)
fun addFriends(first: Person, second: Person): Boolean =
first.addFriend(second) && second.addFriend(first)
fun allPeople() = people.toList().also {
println("Expensive call to get all people")
}
// Note: this can be expensive, so look at the Person.kt class for a hint on how to batch calls
fun findById(id: Int) = people.first { it.id == id }
fun findByIds(ids: List<Int>) = people.filter { it.id in ids }.also {
println("An expensive call to find the people with id $ids")
}
fun nextId() = (people.maxByOrNull { it.id }?.id ?: 0) + 1
}