Created
June 26, 2021 02:32
-
-
Save tpkahlon/24c8362fb5d41ba42dad09e180586e92 to your computer and use it in GitHub Desktop.
Logic - Calculate quantity of fruit with coverage of possible test cases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Write a function that takes input of arrays and loops over them to calculate return values based on some criteria. For example, take this array [['oranges', 1], ['apples', 2], ['grapes', 7]]. Based on this array return total costs if second array property is a quantity and product is first array item. If say Oranges cost $5, and user buys the quantity of 2 or more, apply a 20% discount etc.. Return total cost from array by adding them all up. | |
Let's assume: | |
Orange = $2 | |
Apple = $3 | |
Grapes = $5 | |
*/ | |
const sampleData = [ | |
['oranges', 4], | |
['apples', 23], | |
['grapes'] | |
]; | |
const fruitsList = ['apples', 'oranges', 'grapes']; | |
const areTheseRightFruits = fruits => fruits.filter(fruit => fruitsList.some(setFruit => setFruit === fruit[0])); | |
const hasQuantity = item => item.length === 2; | |
const ifNoItemsText = "You do not have any item to calculate price."; | |
const ifNoQuantityText = "You did not add enough items to calculate price."; | |
const calculatePrice = (data) => { | |
if (!data.length) return ifNoItemsText; | |
let totalCost = 0; | |
const doesItemHasQuantity = data.some(hasQuantity); | |
const itemsWithQuantities = data.filter(hasQuantity); | |
const concernedItems = areTheseRightFruits(itemsWithQuantities); | |
const correctItems = areTheseRightFruits(concernedItems); | |
const correctItemFound = correctItems.length; | |
if (doesItemHasQuantity && correctItemFound) { | |
correctItems.forEach(item => { | |
const fruit = item[0]; | |
const quantity = item[1]; | |
switch (fruit) { | |
case 'oranges': | |
totalCost += 2 * quantity; | |
break; | |
case 'apples': | |
totalCost += 3 * quantity; | |
break; | |
case 'grapes': | |
totalCost += 5 * quantity; | |
break; | |
default: | |
break; | |
} | |
}); | |
return `Your total cost is: ${totalCost}.`; | |
} | |
return ifNoQuantityText; | |
} | |
console.log(calculatePrice(sampleData)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment