Created
February 20, 2023 09:31
-
-
Save prashantsani/fea14a251c20beac32838d8b4702093a to your computer and use it in GitHub Desktop.
Book Store using Factory Function vs Constructor Function
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
// Factory Function | |
function CreateBookStore(inventory) { | |
return { | |
inventory, | |
getInventoryValue() { | |
// if arrow function is used here, this will return `undefined`, | |
// hence using short-hand/object literal for function | |
// this is similar to `getInventoryValue: function () { ......... }` | |
return this.inventory.reduce((total, book) => total + book.price, 0); | |
}, | |
getBookDetails(name) { | |
// Find is better to use here than filter | |
// because we need only ONE book from the inventory | |
return this.inventory.find(book => book.name===name); | |
}, | |
addBookDetails({name, price}){ | |
return this.inventory.push({name, price}) | |
} | |
} | |
} | |
const bookStoreInventory = [ | |
{ | |
name: 'Jay Shetty', | |
price: 300 | |
}, | |
{ | |
name: 'Harry Potter', | |
price: 450 | |
} | |
] | |
var myBookStore = CreateBookStore(bookStoreInventory) | |
myBookStore.addBookDetails({ name: 'Lord of the rings', price: 500}) | |
myBookStore.getInventoryValue() // should return 1250 | |
myBookStore.getBookDetails('Lord of the rings') // {name: 'Lord of the rings', price: 500} | |
// -------------------------------------------------------------------------------- // | |
// Constructor Function | |
function CreateBookStore(inventory) { | |
this.inventory = inventory; | |
} | |
CreateBookStore.prototype.getInventoryValue = function() { | |
return this.inventory.reduce((total, book) => total + book.price, 0); | |
}; | |
CreateBookStore.prototype.getBookDetails = function(name) { | |
return this.inventory.find(book => book.name===name); | |
}; | |
CreateBookStore.prototype.addBookDetails = function({name, price}){ | |
return this.inventory.push({name, price}) | |
} | |
const bookStoreInventory = [ | |
{ | |
name: 'Jay Shetty', | |
price: 300 | |
}, | |
{ | |
name: 'Harry Potter', | |
price: 450 | |
} | |
] | |
var myBookStore = new CreateBookStore(bookStoreInventory) | |
myBookStore.addBookDetails({ name: 'Lord of the rings', price: 500}) | |
myBookStore.getInventoryValue() // should return 1250 | |
myBookStore.getBookDetails('Lord of the rings') // {name: 'Lord of the rings', price: 500} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment