diff --git a/app/src/main/kotlin/app/AppInitializer.kt b/app/src/main/kotlin/app/AppInitializer.kt index fd09b66..4545a72 100644 --- a/app/src/main/kotlin/app/AppInitializer.kt +++ b/app/src/main/kotlin/app/AppInitializer.kt @@ -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)) } } diff --git a/app/src/main/kotlin/command/commands/RemoveById.kt b/app/src/main/kotlin/command/commands/RemoveById.kt new file mode 100644 index 0000000..be4dbf4 --- /dev/null +++ b/app/src/main/kotlin/command/commands/RemoveById.kt @@ -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) + } +} diff --git a/app/src/main/kotlin/manager/CollectionManager.kt b/app/src/main/kotlin/manager/CollectionManager.kt index 54913fe..6506051 100644 --- a/app/src/main/kotlin/manager/CollectionManager.kt +++ b/app/src/main/kotlin/manager/CollectionManager.kt @@ -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 = list fun clear() {