Last active
February 7, 2023 11:43
-
-
Save enio-dev/00fcbf2e5fe4a7176a458393182ac432 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // Faça o calculo do total destes produtos que estão no carrinho | |
| const cart = [ | |
| { | |
| name: 'Pizza de calebreza', | |
| amount: 10, | |
| qty: 2, | |
| addons: [ | |
| { | |
| 'name': 'Extra calabreza', | |
| 'amount': 1.5 | |
| }, | |
| { | |
| 'name': 'Borda recheada', | |
| 'amount': 7 | |
| }, | |
| ], | |
| }, | |
| { | |
| name: 'Carne assada', | |
| amount: 35, | |
| qty: 1, | |
| } | |
| ]; | |
| // Sum addons | |
| const sumAddons = (addons) => { | |
| let amount = 0; | |
| if(addons){ | |
| amount = addons.map(addon => addon.amount).reduce((a, b) => a + b, 0); | |
| } | |
| return amount; | |
| } | |
| // Sum all cart items | |
| const getAmountCart = (cart) => { | |
| return cart.reduce((acc, currentItem) => { | |
| const { amount, qty, addons } = currentItem; | |
| const amountAddons = sumAddons(addons); | |
| return acc + ((amount + amountAddons) * qty); | |
| }, 0) | |
| } | |
| const amountCart = getAmountCart(cart).toLocaleString('pt-br', {style: 'currency', currency: 'BRL'}); | |
| console.log(amountCart); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment