Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save flavioribeirojr/65d558dcc207c4e0cd15027c5dfc9b17 to your computer and use it in GitHub Desktop.
Save flavioribeirojr/65d558dcc207c4e0cd15027c5dfc9b17 to your computer and use it in GitHub Desktop.
function createProduct({ name, price }) {
function getName() {
return name
}
function getPrice() {
return price
}
return {
getName,
getPrice
}
}
function createCart() {
const data = {
items: []
}
function onItemAddedToCart() {
console.log(`The cart has ${data.items.length} items`)
}
function addItem(item) {
return new Promise((resolve) => {
setTimeout(() => {
data.items.push(item)
resolve()
}, 500)
}).then(onItemAddedToCart)
}
function showCartInfo() {
data
.items
.forEach(item => console.log(`${item.getName()}: R$ ${item.getPrice()}`))
}
return {
addItem,
showCartInfo
}
}
const notebook = createProduct({
name: 'Notebook',
price: 1000
})
const smartphone = createProduct({
name: 'Smartphone',
price: 500
})
const myCart = createCart()
Promise.all([
myCart.addItem(notebook),
myCart.addItem(smartphone)
]).then(() => {
myCart.showCartInfo()
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment