diff --git a/composeApp/src/commonMain/kotlin/model/ItemVisitor.kt b/composeApp/src/commonMain/kotlin/model/ItemVisitor.kt new file mode 100644 index 0000000..1c7f741 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/model/ItemVisitor.kt @@ -0,0 +1,8 @@ +package model + +class ItemVisitor(val action: ItemVisitorAction) { + fun visit(item: Item) { + action.accept(item) + item.subItems.forEach { visit(it) } + } +} diff --git a/composeApp/src/commonMain/kotlin/model/ItemVisitorAction.kt b/composeApp/src/commonMain/kotlin/model/ItemVisitorAction.kt new file mode 100644 index 0000000..96b365f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/model/ItemVisitorAction.kt @@ -0,0 +1,5 @@ +package model + +interface ItemVisitorAction { + fun accept(item: Item) +} diff --git a/composeApp/src/commonTest/kotlin/model/ItemVisitorCollector.kt b/composeApp/src/commonTest/kotlin/model/ItemVisitorCollector.kt new file mode 100644 index 0000000..732acf9 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/model/ItemVisitorCollector.kt @@ -0,0 +1,10 @@ +package model + +class ItemVisitorCollector : ItemVisitorAction { + val items = mutableListOf() + + override fun accept(item: Item) { + items.add(item) + } + +} diff --git a/composeApp/src/commonTest/kotlin/model/ItemVisitorVisitsAllSubItemsTest.kt b/composeApp/src/commonTest/kotlin/model/ItemVisitorVisitsAllSubItemsTest.kt new file mode 100644 index 0000000..61753ef --- /dev/null +++ b/composeApp/src/commonTest/kotlin/model/ItemVisitorVisitsAllSubItemsTest.kt @@ -0,0 +1,49 @@ +package model + +import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder +import kotlin.test.Test + +class ItemVisitorVisitsAllSubItemsTest { + + @Test + fun `ItemVisitor visits all sub items`() { + // Given + val item = Item("parent") + val child = Item("child") + val sibling = Item("sibling") + val grandChild = Item("grandChild") + child.add(grandChild) + item.add(child) + item.add(sibling) + + val itemCollector = ItemVisitorCollector() + val visitor = ItemVisitor(itemCollector) + + // When + visitor.visit(item) + + // Then + itemCollector.items shouldContainExactlyInAnyOrder listOf(item, child, sibling, grandChild) + } + + @Test + fun `ItemVisitor starting at child does not get other branches`() { + // Given + val item = Item("parent") + val child = Item("child") + val sibling = Item("sibling") + val grandChild = Item("grandChild") + child.add(grandChild) + item.add(child) + item.add(sibling) + + val itemCollector = ItemVisitorCollector() + val visitor = ItemVisitor(itemCollector) + + // When + visitor.visit(child) + + // Then + itemCollector.items shouldContainExactlyInAnyOrder listOf(child, grandChild) + } +} \ No newline at end of file