drspa44 / Morrisons Groceries - Sort By Price Per Unit

// ==UserScript==
// @name         Morrisons Groceries - Sort By Price Per Unit
// @namespace    https://groceries.morrisons.com/
// @version      1.0
// @description  Add 'Price per unit' sorting options to Morrisons Online Grocery Shop, both ascending and descending. This works for users of the main website where fulfilment is done by warehouse. It does not work for newer Morrisons website, which is https://groceries.store.morrisons.com/.
// @author       drspa44
// @license      MIT
// @match        https://groceries.morrisons.com/*
// @grant        none
// @run-at       document-end
// ==/UserScript==

// This is my first and last userscript. Shout-out to http://www.shelfscraper.co.uk/

(function() {
    'use strict';

    var addOptionsFunction = function () {
        var sortBy = document.querySelector("select[name=sortBy]");
        if (sortBy) {
            if (!sortBy.options[sortBy.options.length-1].value.startsWith("PRICE_PER")) {
                console.log("Adding sort by price per unit options")
                sortBy.options.add(new Option("Price per: Low to High", "PRICE_PER_ASC"));
                sortBy.options.add(new Option("Price per: High to Low", "PRICE_PER_DESC"));
            }
        }
    }
    setInterval(addOptionsFunction, 500); // I can't work out why it doesn't stick the first time.

})();