Advertisement
Guest User

temperature.js

a guest
May 24th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. exports UNITS = {
  2.     KELVIN: 'kelvin',
  3.     FAHRENHEIT: 'fahrenheit',
  4.     CELSIUS: 'celsius'
  5. }
  6.  
  7. /**
  8.  * Converts temperature units.
  9.  *
  10.  * @throws if invalid unit has been passed
  11.  * @param  {String} options.from   from which unit to convert
  12.  * @param  {String} options.to     to which unit to convert
  13.  * @param  {Number} options.amount temperature amount to convert
  14.  * @return {Number}                converted amount
  15.  */
  16. export function convert ({from, to, amount}) {
  17.     if (from === UNITS.FAHRENHEIT && to === UNITS.CELSIUS)  {
  18.         return ...
  19.     }
  20.  
  21.     if (from === UNITS.FAHRENHEIT && to === UNITS.KELVIN)  {
  22.         return ...
  23.     }
  24.  
  25.     if (from === UNITS.KELVIN && to === UNITS.CELSIUS) {
  26.         return ...
  27.     }
  28.  
  29.     if (from === UNITS.KELVIN && to === UNITS.FAHRENHEIT) {
  30.         return ...
  31.     }
  32.  
  33.     if (from === UNITS.CELSIUS && to === UNITS.KELVIN) {
  34.         return ...
  35.     }
  36.  
  37.     if (from === UNITS.CELSIUS && to === UNITS.FAHRENHEIT) {
  38.         return ...
  39.     }
  40.  
  41.     throw new Error(`Invalid units for conversion passed, from ${from}, to ${to}`)
  42. }
  43.  
  44. /**
  45.  * Reads user preferred units, defaults to Celsius.
  46.  *
  47.  * @return {String} Temperature units
  48.  */
  49. export function getUnits () {
  50.     try {
  51.         const unitSerialized = localStorage.getItem('units')
  52.         const unit = JSON.parse(unitsSerialized)
  53.  
  54.         if (!Object.values(UNITS).includes(unit)) {
  55.             setUnits(UNITS.CELSIUS)
  56.             return UNITS.CELSIUS
  57.         }
  58.  
  59.         return unit
  60.     } catch () {
  61.         // if local storage is empty or malformed, it'll probably throw, set it up properly
  62.         setUnits(UNITS.CELSIUS)
  63.         return UNITS.CELSIUS
  64.     }
  65. }
  66.  
  67. /**
  68.  * Sets user's preferred units
  69.  *
  70.  * @throws  If invalid value is passed
  71.  * @return {String} Temperature units
  72.  */
  73. export function setUnits (unit) {
  74.     if (Object.values(UNITS).includes(unit)) {
  75.         localStorage.setItem('units', JSON.stringify(unit))
  76.     } else {
  77.         throw new Error(`Invalid unit passed: ${unit}`)
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement