If you're looking to dive into the world of Array.reduce
, here's a solution that can serve as a starting point for your exploration. While it may not be the most optimized approach, it offers a foundation from which you can build upon and optimize further. By honing your skills with this concept, you can achieve the desired results in terms of processing efficiency and complexity.
Check out this Repl Example for more hands-on experience.
The function cheapestStoreForRecipe
takes in two arguments: recipe
and storeCollection
. It returns a list of stores along with their corresponding invoices for the given recipe, showcasing the cost of each ingredient item and the total cost of the recipe.
Here's an overview of how the function works:
1. Iterate through each store in the storeCollection
.
2. For each store, iterate through the items in the recipe.
3. If there is a match between a recipe item and a store inventory item, calculate the quantity, unit, total cost of the item, and eventually the total cost of the entire recipe.
function cheapestStoreForRecipe(recipe, storeCollection){
return Object.entries(storeCollection)
.reduce((_storeCollection, [storeName, storeInventory]) => {
let storeInvoice = Object.entries(recipe)
.reduce((_recipe, [itemName, itemQuantity]) => {
let storeInventoryItem = storeInventory[itemName]
if(storeInventoryItem) {
_recipe.invoice[itemName] = {
quantity: itemQuantity,
unit: storeInventoryItem,
total: itemQuantity * storeInventoryItem,
}
_recipe.total += _recipe.invoice[itemName].total
}
return _recipe
}, {
invoice: {},
total: 0,
})
_storeCollection[storeName] = storeInvoice
return _storeCollection
}, {
Brutto: {},
Edoka: {},
Were: {},
})
}
Below is a sample representation of the invoices generated by the function:
{
"Brutto": {
"invoice": {
"potato": {
"quantity": 3,
"unit": 3,
"total": 9
},
"onion": {
"quantity": 1,
"unit": 5,
"total": 5
},
"corn": {
"quantity": 5,
"unit": 2,
"total": 10
}
},
"total": 24
},
"Edoka": {
"invoice": {
"potato": {
"quantity": 3,
"unit": 5,
"total": 15
},
"onion": {
"quantity": 1,
"unit": 4,
"total": 4
},
"corn": {
"quantity": 5,
"unit": 3,
"total": 15
}
},
"total": 34
},
"Were": {
"invoice": {
"potato": {
"quantity": 3,
"unit": 3,
"total": 9
},
"onion": {
"quantity": 1,
"unit": 5,
"total": 5
},
"corn": {
"quantity": 5,
"unit": 2,
"total": 10
}
},
"total": 24
}
}