javascriptfunctionparametersunits-of-measurement

Electricity units calculator


I'm basically using functions and if else if statements to build an electricity reading calculator.

The units given is 1236 which is a parameter of the function called elecReading. This will be used as the amount of units used and it will calculate the amount that must be paid.

However, the first 0-500 units are billed at $1 per unit. The next 500-1000 units are billed at $1.10 a unit, and over 1000 units are billed at $3.20 a unit. For example, if I used 1000 units, my bill would be $1050.

I'm unsure how I can get this working without breaking down 1236 into singular numbers manually. How can I write a calculator like this with JavaScript?

Obviously I'm not asking for the complete answer, but a push in the right direction would be very helpful at this stage!

Thanks for the help in advance


Solution

  • The static version would be something like:

    var UNIT_PRICE_1001_OVER = 3.20;
    var UNIT_PRICE_501_1000 = 1.10;
    var UNIT_PRICE_UNDER_500 = 1.00;
    function elecReading(units) {
        var price = 0;
    
        if (units > 1000) {
            price += (units-1000) * UNIT_PRICE_1001_OVER;
            units = 1000;
        }
        if (units > 500) {
            price += (units - 500) * UNIT_PRICE_501_1000;
            units = 500;
        }
        price += units * UNIT_PRICE_UNDER_500;
    
        return price;
    }
    

    This is assuming the unit price ranges are 1-500, 501-1000, 1001-Inf. Obviously this can be done more generally / with less hardcoding, using a list of objects representing a price range + price per unit in said range.