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