feat(command): add RemoveById command

This commit is contained in:
2026-03-04 12:10:58 +03:00
parent d991fe02c4
commit 20d98bf74b
3 changed files with 37 additions and 4 deletions

View File

@@ -6,6 +6,7 @@ import command.commands.Clear
import command.commands.Exit
import command.commands.Help
import command.commands.Info
import command.commands.RemoveById
import command.commands.Show
import command.commands.Update
import io.IOHandler
@@ -26,5 +27,6 @@ class AppInitializer {
commandManager.register(Show(io, collectionManager))
commandManager.register(Info(io, collectionManager))
commandManager.register(Update(io, collectionManager))
commandManager.register(RemoveById(io, collectionManager))
}
}

View File

@@ -0,0 +1,28 @@
package command.commands
import command.Command
import io.IOHandler
import manager.CollectionManager
class RemoveById(
private val io: IOHandler,
private val collectionManager: CollectionManager,
) : Command {
override val name = "remove_by_id"
override val description = "remove element by id"
override fun execute(args: String) {
val id = args.trim().toLongOrNull()
if (id == null) {
io.println("введите id, к примеру: remove_by_id 5")
return
}
if (collectionManager.getCollection().none { it.id == id }) {
io.println("элемент с id=$id не найден")
return
}
collectionManager.removeById(id)
}
}

View File

@@ -38,10 +38,7 @@ class CollectionManager(
id: Long,
newProduct: Product,
) {
val index =
list.indexOfFirst {
it.id == id
}
val index = list.indexOfFirst { it.id == id }
val old = list[index]
@@ -56,6 +53,12 @@ class CollectionManager(
io.println("элемент обновлен")
}
fun removeById(id: Long) {
val index = list.indexOfFirst { it.id == id }
list.removeAt(index)
io.println("элемент удален")
}
fun getCollection(): LinkedList<Product> = list
fun clear() {