This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
FunctionProject/api/assets/functions/main/convertTemperature.js

54 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

2020-08-03 12:04:07 +02:00
const errorHandling = require('../../utils/errorHandling')
const { requiredFields, generalError } = require('../../config/errors')
const formatNumberResult = require('../secondary/formatNumberResult')
2020-08-03 12:04:07 +02:00
/**
* @description Convertis des °C en °F et l'inverse aussi.
* @param {Number} degree - Nombre de degrès
* @param {String} unit - Unité du nombre (°C ou °F) après conversion
* @returns {Object} false si arguments non valides et sinon un objet contenant la string et le nombre résultat
* @examples convertTemperature(23, '°F') { result: 73.4, resultHTML: "73.4 °F" }
*/
2020-08-03 12:04:07 +02:00
function convertTemperature (degree, unit) {
let temperatureValue = 0
if (unit === '°C') {
2020-08-03 14:14:45 +02:00
temperatureValue = ((degree - 32) * 5) / 9
2020-08-03 12:04:07 +02:00
} else if (unit === '°F') {
2020-08-03 14:14:45 +02:00
temperatureValue = (degree * 9) / 5 + 32
2020-08-03 12:04:07 +02:00
} else {
return false
}
return {
result: temperatureValue,
2020-08-03 14:14:45 +02:00
resultHTML: `<p>${formatNumberResult(degree)} ${
unit === '°C' ? '°F' : '°C'
} = ${formatNumberResult(temperatureValue)} ${unit}</p>`
2020-08-03 12:04:07 +02:00
}
}
/* OUTPUTS */
2020-08-03 12:04:07 +02:00
module.exports = ({ res, next }, argsObject) => {
let { degree, unitToConvert } = argsObject
2020-08-03 12:04:07 +02:00
// S'il n'y a pas les champs obligatoire
if (!(degree && unitToConvert)) {
return errorHandling(next, requiredFields)
}
2020-08-03 12:04:07 +02:00
// Si ce n'est pas un nombre
degree = parseFloat(degree)
if (isNaN(degree)) {
2020-08-03 14:14:45 +02:00
return errorHandling(next, {
message: 'Veuillez rentré un nombre valide.',
statusCode: 400
})
2020-08-03 12:04:07 +02:00
}
const result = convertTemperature(degree, unitToConvert)
if (!result) {
return errorHandling(next, generalError)
}
return res.status(200).json(result)
}