Created
January 14, 2024 12:28
-
-
Save geraldotech/03fe1eda913a38079b66bb98d29d5d4c to your computer and use it in GitHub Desktop.
Cart Shopping purchase.js
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
// evita adicionar o mesmo item no carrinho, apenas increment quantidade | |
const cart = [] | |
function addToCart(product){ | |
// get index se o item tem no carrinho | |
const checkCartItem = cart.findIndex(pro => pro.id === product.id) | |
if(checkCartItem > -1){ | |
// item existe apenas increment quant | |
cart[checkCartItem].quat++ | |
} else { | |
// item nao existe add item to cart | |
cart.push(product) | |
} | |
// chamar a func que faz soma | |
somar() | |
} | |
function somar(){ | |
const soma = cart.reduce((accu, curval) => { | |
return accu + parseInt(curval.quat) * +curval.price // quant * valor | |
}, 0) | |
return soma.toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'}); | |
} | |
// produtcs para adicionar ao Cart | |
const cookies = {id: 1, item: 'cookies', price: 2.85, quat: 1} | |
const kitkat = {id: 5, item: 'Kit Kat', price: 2.25, quat: 1} | |
// usersOnClick | |
addToCart(cookies) | |
addToCart(kitkat) | |
addToCart(cookies) | |
addToCart(kitkat) | |
console.log(cart); | |
console.log(somar()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment