Enhanced Object Literals

//ES5
function createBookShop(inventory) {
    return {
        inventory: inventory,
        inventoryValue: function() {
            return this.inventory.reduce((total,book) => total + book.price, 0); 
        }, 
        priceForTitle: function(title) {
            return this.inventory.find(book => book.title === title).price; 
        }
    }
}

const inventory = [
    {title: 'Harry Potter', price: 10},
    {title: 'Eloquent Potter', price: 120}
]

const bookShop = createBookShop(inventory);

//ES6
function createBookShop(inventory) {
    return {
        inventory,//In ES6, when the key and the value are the exact same name, we can just use inventory 
        inventoryValue() { //If you have a key value pair, where the value is a function, you can omit the function
            return this.inventory.reduce((total,book) => total + book.price, 0); 
        }, 
        priceForTitle(title) {
            return this.inventory.find(book => book.title === title).price; 
        }
    }
}

results matching ""

    No results matching ""