kotlin-koans icon indicating copy to clipboard operation
kotlin-koans copied to clipboard

Collections Fold task should be changed

Open NorthFury opened this issue 7 years ago • 2 comments

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)
            }

NorthFury avatar Sep 12 '17 12:09 NorthFury

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.

sultanahamer avatar Mar 31 '18 08:03 sultanahamer

That test is super confusing, definitely should be renamed to 'testGetProductsOrderedByAllCustomers' or 'testGetProductsOrderedByEveryCustomer'

lewisevans avatar Sep 27 '18 14:09 lewisevans