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

50 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-03-19 22:59:06 +01:00
const errorHandling = require('../../utils/errorHandling');
const { requiredFields, generalError } = require('../../config/errors');
const formatNumberResult = require('../secondary/formatNumberResult');
/**
* @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, '°C') { result: 73.4, resultHTML: "73.4 °F" }
*/
function convertTemperature(degree, unit) {
let temperatureValue = 0;
if (unit === "°C") {
temperatureValue = (degree - 32) * 5/9;
}
else if (unit === "°F") {
temperatureValue = ((degree * 9/5) + 32);
}
else {
return false;
}
return {
result: temperatureValue,
resultHTML: `<p>${formatNumberResult(temperatureValue)} ${unit}</p>`
};
}
/* OUTPUTS */
module.exports = convertTemperatureOutput = ({ res, next }, argsObject) => {
let { degree, unitToConvert } = argsObject;
// S'il n'y a pas les champs obligatoire
if (!(degree && unit)) {
2020-03-19 22:59:06 +01:00
return errorHandling(next, requiredFields);
}
// Si ce n'est pas un nombre
degree = parseInt(degree);
if (isNaN(degree)) {
2020-03-19 22:59:06 +01:00
return errorHandling(next, { message: "Veuillez rentré un nombre valide.", statusCode: 400 });
}
const result = convertTemperature(degree, unitToConvert);
if (!result) {
2020-03-19 22:59:06 +01:00
return errorHandling(next, generalError);
}
2020-03-19 23:21:20 +01:00
return res.status(200).json(result);
}