Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- exports UNITS = {
- KELVIN: 'kelvin',
- FAHRENHEIT: 'fahrenheit',
- CELSIUS: 'celsius'
- }
- /**
- * Converts temperature units.
- *
- * @throws if invalid unit has been passed
- * @param {String} options.from from which unit to convert
- * @param {String} options.to to which unit to convert
- * @param {Number} options.amount temperature amount to convert
- * @return {Number} converted amount
- */
- export function convert ({from, to, amount}) {
- if (from === UNITS.FAHRENHEIT && to === UNITS.CELSIUS) {
- return ...
- }
- if (from === UNITS.FAHRENHEIT && to === UNITS.KELVIN) {
- return ...
- }
- if (from === UNITS.KELVIN && to === UNITS.CELSIUS) {
- return ...
- }
- if (from === UNITS.KELVIN && to === UNITS.FAHRENHEIT) {
- return ...
- }
- if (from === UNITS.CELSIUS && to === UNITS.KELVIN) {
- return ...
- }
- if (from === UNITS.CELSIUS && to === UNITS.FAHRENHEIT) {
- return ...
- }
- throw new Error(`Invalid units for conversion passed, from ${from}, to ${to}`)
- }
- /**
- * Reads user preferred units, defaults to Celsius.
- *
- * @return {String} Temperature units
- */
- export function getUnits () {
- try {
- const unitSerialized = localStorage.getItem('units')
- const unit = JSON.parse(unitsSerialized)
- if (!Object.values(UNITS).includes(unit)) {
- setUnits(UNITS.CELSIUS)
- return UNITS.CELSIUS
- }
- return unit
- } catch () {
- // if local storage is empty or malformed, it'll probably throw, set it up properly
- setUnits(UNITS.CELSIUS)
- return UNITS.CELSIUS
- }
- }
- /**
- * Sets user's preferred units
- *
- * @throws If invalid value is passed
- * @return {String} Temperature units
- */
- export function setUnits (unit) {
- if (Object.values(UNITS).includes(unit)) {
- localStorage.setItem('units', JSON.stringify(unit))
- } else {
- throw new Error(`Invalid unit passed: ${unit}`)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement