Created
December 30, 2018 17:21
-
-
Save flavioribeirojr/65d558dcc207c4e0cd15027c5dfc9b17 to your computer and use it in GitHub Desktop.
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
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