// NoteService
package com.eltex.domain
import arrow.core.Either
import com.eltex.data.Note
import com.eltex.utils.NoteNotFound
interface NoteService {
/**
* Если id == 0, создаёт новую, если id равен существующей заметке, сохраняет
* В случае, если указан некорректный id, выводит NoteNotFound
* При обновлении updatedAt должно заполняться текущим временем
* @throws IllegalArgumentException
*/
fun save(note: Note): Either<NoteNotFound, Note>
/**
* Возвращает копию внутреннего списка
*/
fun getAll(): List<Note>
/**
* Возвращает список текстов без повторов
*/
fun getAllUniqueTexts(): List<String>
/**
* Возвращает несколько заметок старше указанного id
* @param count – сколько заметок отсчитать
* @param id - относительно какого элемента отсчитывать
*/
fun getBefore(count: Int, id: Long): List<Note>
/**
* Возвращает несколько заметок новее указанного id
* @param count – сколько заметок отсчитать
* @param id - относительно какого элемента отсчитывать
*/
fun getAfter(count: Int, id: Long): List<Note>
}
// NoteServiceImpl
package com.eltex.data
import arrow.core.Either
import arrow.core.left
import arrow.core.right
import com.eltex.domain.NoteService
import com.eltex.utils.NoteNotFound
import java.time.Instant
class NoteServiceImpl : NoteService {
private val noteList = mutableListOf<Note>()
private var noteId: Long = 1L
override fun save(note: Note): Either<NoteNotFound, Note> {
return when (note.id) {
0L -> {
noteList.add(
Note(id = noteId++, text = note.text)
)
noteList.last().right()
}
else -> {
val noteIndex = noteList.indexOfFirst { it.id == note.id }
if (noteIndex > 0) {
noteList[noteIndex] = noteList[noteIndex].copy(text = note.text, updatedAt = Instant.now())
noteList[noteIndex].right()
} else {
NoteNotFound("Заметка с id ${note.id} не найдена").left()
}
}
}
}
override fun getAll(): List<Note> = noteList
override fun getAllUniqueTexts(): List<String> =
noteList.asSequence()
.map { it.text }
.distinct()
.toList()
override fun getBefore(count: Int, id: Long): List<Note> =
noteList.dropLastWhile { it.id >= id }
.sortedByDescending { it.id }
.take(count)
override fun getAfter(count: Int, id: Long) =
noteList.dropWhile { it.id <= id }
.sortedBy { it.id }
.take(count)
}
// Note
package com.eltex.data
import java.time.Instant
data class Note (
val id: Long = 0L,
val text: String = "",
val createdAt: Instant = Instant.now(),
val updatedAt: Instant = Instant.now()
)
println(noteServiceImpl.getAll())
println(
noteServiceImpl.getAllUniqueTexts())
println(
noteServiceImpl.getBefore(3, 8L)
)
println(
noteServiceImpl.getAfter(3, 3L)
)