calculations/emissions.js

  1. /**
  2. * Emission related calculations
  3. * @module
  4. * @since 0.0.3
  5. */
  6. import { gallonsToLitres, mpgToL100km, milesToKM } from '../maths/conversions';
  7. import { co2_kg_per_litre } from '../maths/constants';
  8. import { roundToDP } from '../maths/util';
  9. /**
  10. * co2 by a number of units of fuel
  11. * @param {number} num_amount Quantity of fuel
  12. * @param {string} from_unit What unit the fuel quantity is in
  13. * @param {string} fuel_type Type of fuel i.e diesel or petrol
  14. * @returns {number} Total kg of CO2 for fuel supplied
  15. */
  16. const getCo2ByAmountOfFuel = (
  17. num_amount,
  18. from_unit,
  19. fuel_type,
  20. ) => {
  21. let _num_amount = num_amount;
  22. // convert to litres
  23. if (from_unit === 'gallons') {
  24. _num_amount = gallonsToLitres(_num_amount);
  25. }
  26. return roundToDP((_num_amount * co2_kg_per_litre[fuel_type]), 7);
  27. };
  28. /**
  29. * co2 by amount of money spent
  30. * @param {number} num_amount Quantity of fuel
  31. * @param {string} from_unit What unit the fuel quantity is in
  32. * @param {string} fuel_type Type of fuel i.e diesel or petrol
  33. * @returns {number} Total kg of CO2 for fuel supplied
  34. */
  35. const getCo2ByAmountOfMoney = (
  36. pounds_spent,
  37. pence_per_litre,
  38. fuel_type,
  39. ) => {
  40. // get number of litres used by calculating amount spent in pence divided by
  41. // cost in pence per litre
  42. const num_litres = (pounds_spent * 100) / pence_per_litre;
  43. // calculate co2 from litres used
  44. return getCo2ByAmountOfFuel(num_litres, 'litres', fuel_type);
  45. };
  46. /**
  47. * co2 by amount of fuel consumed
  48. * @param {number} num_distance Miles or KM travelled
  49. * @param {string} distance_unit Miles or KM
  50. * @param {number} num_consumption Quantity of fuel
  51. * @param {string} consumption_unit l/100km or mpg
  52. * @param {string} fuel_type Type of fuel i.e diesel or petrol
  53. * @returns {number} Total kg of CO2
  54. */
  55. const getCo2ByDistance = (
  56. num_distance,
  57. distance_unit,
  58. num_consumption,
  59. consumption_unit,
  60. fuel_type,
  61. ) => {
  62. let _num_consumption = num_consumption;
  63. let _num_distance = num_distance;
  64. // convert to l100km if mpg
  65. if (consumption_unit === 'mpg') {
  66. _num_consumption = mpgToL100km(_num_consumption);
  67. }
  68. // convert to km from if miles
  69. if (distance_unit === 'miles') {
  70. _num_distance = milesToKM(_num_distance);
  71. }
  72. // find out how many litres have been used
  73. const num_litres = _num_distance * (_num_consumption / 100);
  74. // calculate co2 from litres used
  75. return getCo2ByAmountOfFuel(num_litres, 'litres', fuel_type);
  76. };
  77. export {
  78. getCo2ByAmountOfFuel,
  79. getCo2ByAmountOfMoney,
  80. getCo2ByDistance,
  81. };