Shopping List

A simple shopping list that looks up item cost and updates the total.

Visit site
  • HTML
  • Sass (responsive)
  • JS
  • jQuery
  • RegExp

Aug 24, 2016

Challenges

1Some grocery items are priced by weight, not by quantity and I wanted to allow for this. I created a JSON file that listed grocery items along with a price-per-unit and price-per-kilo where applicable. I used regular expressions to extract numbers from the input quantity and look for "kg", which if present, would then use the price-per-kilo multiplier for the item (Snippet 1). A few problems with this is that the quantity input is too permissive: if the user enters "12.3kj" the form won't complain but simply use 12.3 as price multiplier – form validation needs to be added.

function getPrice( item, quantity ) {
    // extracts digits from string and coerces to number
    // determines if "kg" was included look for price-per-kilo
    // if price-per-kilo unavailable, default to price-per-unit
    // return price to two decimal places
    var priceData = {
        amount: 0,
        multiplier: 0
    };
    var amount = +quantity.match(/\d*\.?\d*/)[0];
    priceData.amount = amount;

    if (/([kK][gG][sS]?)$/.test(quantity)) {
        priceData.multiplier = item.ppKilo ? item.ppKilo : item.ppUnit;
    } else {
        priceData.multiplier = item.ppUnit;
    }

    return toTwoDecimals(priceData.amount * priceData.multiplier);
}
Snippet 1. Function that returns the cost of an item given its quantity in units or kilograms.

2Displaying a list of partially matching results as a user types in the text field is common pattern I wanted to replicate. The solution in this case was to use jQuery to listen for keyup events and use indexOf() to check if the user input matches any of the listed products. If so, they are displayed beneath the text field. The function handling this logic became quite complex and if I were to do this again I would look for ways to break it into smaller functions and spend some time looking at how other developers solved this.

Addendum

Colour theme ideas taken from CSS Weekly newsletter. Wireframes for smallish and bigish screens made in Sketch (Figure 1). "Open Sans" font from Google Fonts.

Figure 2. Shopping list wireframes