Skip to content

Instantly share code, notes, and snippets.

@wtshek
Last active October 12, 2019 06:10
Show Gist options
  • Save wtshek/28b89c064a37d7c870c4681dc9fa5cc5 to your computer and use it in GitHub Desktop.
Save wtshek/28b89c064a37d7c870c4681dc9fa5cc5 to your computer and use it in GitHub Desktop.
#Pattern #OOP Icey Factory
// how to do inheritance
// passing in the prototype function
// Object.freeze make only shallow copies
function makeProductList({ productDb }) {
return Object.freeze({
addProduct,
empty,
getProducts,
removeProduct,
// others
)}
// definitions for
// addProduct, etc…
}
function makeShoppingCart(productList) {
return Object.freeze({
items: productList,
someCartSpecificMethod,
// …
)}
function someCartSpecificMethod () {
// code
}
}
const productDb = []
const productList = makeProductList({ productDb })
const cart = makeShoppingCart(productList)
cart.items.addProduct()
// return on top to make a summary
// no need to use this and class syntax
// object composition
export default function makeShoppingCart({
db
}) {
return Object.freeze({
addProduct,
empty,
getProducts,
removeProduct,
// others
})
function addProduct (product) {
db.push(product)
}
function empty () {
db = []
}
function getProducts () {
return Object
.freeze([...db])
}
function removeProduct (id) {
// remove a product
}
// other functions
}
// someOtherModule.js
const db = []
const cart = makeShoppingCart({ db })
cart.addProduct({
name: 'foo',
price: 9.99
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment