Thursday 26 November 2020

Enhancing the performance of a for each loop that has an inner for each loop

AS 4.1.1
Kotlin 1.4.10

Writing a for loop with an inner forloop to check stock items quantities. Checking if the item in the cart's quantity is greater than the current stock item's quantity.

Using a inner for loop seems to be a very naive approach even though it works.

Just wondering if there is a better way to do this:

For the curentSkuQuantity I have a data class like this:

data class CurrentSkuQuantity(
    val sku: String,
    val quantity: Int)

After RxJava return success with the current stock levels I check that the sku's are the same as the cart item. And then compare their quantities to see there is enough.

onSuccess = { currentSkuQuantity ->
                    val cartList = cartProvider.cdsCart?.items
                    var hasStockShortage = false

                    currentSkuQuantity.forEach { currentStockItem ->
                        cartList?.forEach { cartItem ->
                            // Check that we are checking the correct sku item
                            if(currentStockItem.sku == cartItem.sku) {
                                // Check the quantity is enough
                                if(cartItem.qty > currentStockItem.quantity) {
                                    // Not enough stock
                                    hasStockShortage = true
                                }
                            }
                        }
                    }

                    if(!hasStockShortage) {
                        gotoCheckout()
                    }
                    else {
                        gotoCart()
                    }
                }


from Enhancing the performance of a for each loop that has an inner for each loop

No comments:

Post a Comment