kotlin-koans
kotlin-koans copied to clipboard
Collections Fold task should be changed
I can't think of any scenario where I would solve the Collections Fold task using fold
efficiently. I think it should be changed to showcase a realistic scenario for fold
. This task could be reused as an example for reduce
though. Here is a solution I think is good for this task.
val customerProductSets = this.customers.map {
it.orders.flatMap { it.products }.toSet()
}
if (customerProductSets.isEmpty()) {
return emptySet<Product>()
}
return customerProductSets.reduce { acc, products -> acc.intersect(products) }
Or an even more optimized solution:
if (this.customers.isEmpty()) return emptySet<Product>()
return this.customers.asSequence()
.map { it.orders.flatMap { it.products }.toSet() }
.reduce { acc, products ->
acc.intersect(products)
}
Also, the function name in N22Fold.kt is getSetOfProductsOrderedByEachCustomer which is confusing to the actual test testGetProductsOrderedByAllCustomers.
I inferred code to get all products ordered and test to get common product ordered by all customers.
That test is super confusing, definitely should be renamed to 'testGetProductsOrderedByAllCustomers' or 'testGetProductsOrderedByEveryCustomer'