From 5e7aa74f23683c1c0e0beade00fbb9ada66acab0 Mon Sep 17 00:00:00 2001 From: Ahmed Hosny Date: Sun, 18 May 2025 15:44:35 +0300 Subject: [PATCH] refactor userCache currentPermission as lazy --- src/main/kotlin/presentation/CategoryUI.kt | 39 ++++++++++++---------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/src/main/kotlin/presentation/CategoryUI.kt b/src/main/kotlin/presentation/CategoryUI.kt index 6d588de..6958f0b 100644 --- a/src/main/kotlin/presentation/CategoryUI.kt +++ b/src/main/kotlin/presentation/CategoryUI.kt @@ -12,31 +12,36 @@ class CategoryUI( private val viewer: Viewer, private val reader: Reader, private val userCache: UserCache +) : UiRunner { -): UiRunner { + private val allowed by lazy { children.filter { it.isAllowed(userCache.currentPermission) } } override fun run() { - val permission = userCache.currentPermission - val allowed = children.filter { it.isAllowed(permission) } - if (allowed.isEmpty()) { viewer.show("No available actions in $label.") return } + executeMenu() + } + + private fun executeMenu() { while (true) { - viewer.show("=== $label ===") - allowed.sortedBy { it.id } - .forEach { viewer.show("${it.id} – ${it.label}") } - viewer.show("X – Back") - - when (val input = reader.read()?.trim()?.uppercase(Locale.getDefault())) { - null,"X" -> return - else -> allowed - .firstOrNull { it.id == input.toIntOrNull() } - ?.run() - ?: viewer.show("Invalid choice") - } + showMenu() + val input = reader.read()?.trim()?.uppercase(Locale.getDefault()) + + if (input.isNullOrEmpty() || input == "X") return + + allowed.firstOrNull { it.id == input.toIntOrNull() } + ?.run() + ?: viewer.show("Invalid choice") } } -} \ No newline at end of file + + private fun showMenu() { + viewer.show("=== $label ===") + allowed.sortedBy { it.id } + .forEach { viewer.show("${it.id} – ${it.label}") } + viewer.show("X – Back") + } +}