Extra study: Build a Cash Register

Extra study: Build a Cash Register

Every time I give this module a visit it ends up drawing me in. Tonight it is this,


    price: function(item) {
        switch (item){
            case "eggs": return 0.98;
            case "milk": return 1.23;
            case "magazine": return 4.99;
            case "chocolate": return 0.45;
            default: return false;
        }
    },
    scan: function(item, quantity) {
        var price = this.price(item);
        if (price) {
            this.add(quantity * price);
            return true;
        }
        return false;
    },

This reduces the price list to a case-value pair, setting the stage for a plain object approach.

var prices = {
    "eggs": 0.98,
    "milk": 1.23,
    "magazine": 4.99,
    "chocolate": 0.45
};

And the price method becomes,

    price: function(item) {
        if (prices.hasOwnProperty(item)) {
            return prices[item];
        }
        return false;
    },

This passes the SCT, as well as the previous.

Last post, promiseā€¦

The above sets the stage for a simple ternary expression approach:

    price: function(item) {
        return prices.hasOwnProperty(item) ? prices[item] : false;
    },

Also passes.