Last active
October 12, 2019 06:10
-
-
Save wtshek/28b89c064a37d7c870c4681dc9fa5cc5 to your computer and use it in GitHub Desktop.
#Pattern #OOP Icey Factory
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
// 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() |
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
// 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