calculations/emissions.js

/**
 * Emission related calculations
 * @module
 * @since 0.0.3
 */

import { gallonsToLitres, mpgToL100km, milesToKM } from '../maths/conversions';
import { co2_kg_per_litre } from '../maths/constants';
import { roundToDP } from '../maths/util';

/**
 * co2 by a number of units of fuel
 * @param {number} num_amount Quantity of fuel
 * @param {string} from_unit What unit the fuel quantity is in
 * @param {string} fuel_type Type of fuel i.e diesel or petrol
 * @returns {number} Total kg of CO2 for fuel supplied
 */
const getCo2ByAmountOfFuel = (
    num_amount,
    from_unit,
    fuel_type,
) => {
    let _num_amount = num_amount;

    // convert to litres
    if (from_unit === 'gallons') {
        _num_amount = gallonsToLitres(_num_amount);
    }

    return roundToDP((_num_amount * co2_kg_per_litre[fuel_type]), 7);
};

/**
 * co2 by amount of money spent
 * @param {number} num_amount Quantity of fuel
 * @param {string} from_unit What unit the fuel quantity is in
 * @param {string} fuel_type Type of fuel i.e diesel or petrol
 * @returns {number} Total kg of CO2 for fuel supplied
 */
const getCo2ByAmountOfMoney = (
    pounds_spent,
    pence_per_litre,
    fuel_type,
) => {
    // get number of litres used by calculating amount spent in pence divided by
    // cost in pence per litre
    const num_litres = (pounds_spent * 100) / pence_per_litre;

    // calculate co2 from litres used
    return getCo2ByAmountOfFuel(num_litres, 'litres', fuel_type);
};

/**
 * co2 by amount of fuel consumed
 * @param {number} num_distance Miles or KM travelled
 * @param {string} distance_unit Miles or KM
 * @param {number} num_consumption Quantity of fuel
 * @param {string} consumption_unit l/100km or mpg
 * @param {string} fuel_type Type of fuel i.e diesel or petrol
 * @returns {number} Total kg of CO2
 */
const getCo2ByDistance = (
    num_distance,
    distance_unit,
    num_consumption,
    consumption_unit,
    fuel_type,
) => {
    let _num_consumption = num_consumption;
    let _num_distance = num_distance;

    // convert to l100km if mpg
    if (consumption_unit === 'mpg') {
        _num_consumption = mpgToL100km(_num_consumption);
    }

    // convert to km from if miles
    if (distance_unit === 'miles') {
        _num_distance = milesToKM(_num_distance);
    }

    // find out how many litres have been used
    const num_litres = _num_distance * (_num_consumption / 100);

    // calculate co2 from litres used
    return getCo2ByAmountOfFuel(num_litres, 'litres', fuel_type);
};

export {
    getCo2ByAmountOfFuel,
    getCo2ByAmountOfMoney,
    getCo2ByDistance,
};