Hotfix: Nom des dossiers + Ajout /functions/slug
This commit is contained in:
12
api/assets/config/config.js
Normal file
12
api/assets/config/config.js
Normal file
@ -0,0 +1,12 @@
|
||||
const config = {
|
||||
PORT: process.env.PORT || 8080,
|
||||
WEATHER_API_KEY: process.env.OpenWeatherMap_API_KEY,
|
||||
DATABASE: {
|
||||
host: process.env.DB_HOST,
|
||||
name: process.env.DB_NAME,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = config;
|
18
api/assets/config/errors.js
Normal file
18
api/assets/config/errors.js
Normal file
@ -0,0 +1,18 @@
|
||||
const errors = {
|
||||
generalError: {
|
||||
message: "Vous n'avez pas rentré de valeur valide.",
|
||||
statusCode: 400
|
||||
},
|
||||
|
||||
serverError: {
|
||||
message: "Le serveur n'a pas pu traiter votre requête.",
|
||||
statusCode: 500
|
||||
},
|
||||
|
||||
requiredFields: {
|
||||
message: "Vous devez remplir tous les champs...",
|
||||
statusCode: 400
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = errors;
|
31
api/assets/functions/functionObject.js
Normal file
31
api/assets/functions/functionObject.js
Normal file
@ -0,0 +1,31 @@
|
||||
const { randomNumberOutput } = require('./main/randomNumber');
|
||||
const { convertArabicToRomanOutput, convertRomanToArabicOutput } = require('./main/convertRomanArabicNumbers');
|
||||
const { convertDistanceOutput } = require('./main/convertDistance');
|
||||
const { convertTemperatureOutput } = require('./main/convertTemperature');
|
||||
const { armstrongNumberOutput } = require('./main/armstrongNumber');
|
||||
const { weatherRequestOutput } = require('./main/weatherRequest');
|
||||
const { convertCurrencyOutput } = require('./main/convertCurrency');
|
||||
const { calculateAgeOutput } = require('./main/calculateAge');
|
||||
const { heapAlgorithmOutput } = require('./main/heapAlgorithm');
|
||||
const { convertEncodingOutput } = require('./main/convertEncoding');
|
||||
|
||||
const functionObject = {
|
||||
randomNumber : randomNumberOutput,
|
||||
convertArabicToRoman: convertArabicToRomanOutput,
|
||||
convertRomanToArabic: convertRomanToArabicOutput,
|
||||
convertDistance : convertDistanceOutput,
|
||||
convertTemperature : convertTemperatureOutput,
|
||||
armstrongNumber : armstrongNumberOutput,
|
||||
weatherRequest : weatherRequestOutput,
|
||||
convertCurrency : convertCurrencyOutput,
|
||||
calculateAge : calculateAgeOutput,
|
||||
heapAlgorithm : heapAlgorithmOutput,
|
||||
convertEncoding : convertEncodingOutput
|
||||
};
|
||||
|
||||
// Choisi la fonction à exécuter
|
||||
function functionToExecute(option) {
|
||||
return functionObject[option];
|
||||
}
|
||||
|
||||
module.exports = functionToExecute;
|
46
api/assets/functions/main/armstrongNumber.js
Normal file
46
api/assets/functions/main/armstrongNumber.js
Normal file
@ -0,0 +1,46 @@
|
||||
const errorHandling = require('../../utils/errorHandling');
|
||||
const { requiredFields } = require('../../config/errors');
|
||||
const formatNumberResult = require('../secondary/formatNumberResult');
|
||||
|
||||
/**
|
||||
* @description Vérifie si un nombre fait partie des nombres d'Armstrong.
|
||||
* @param {Number} number - Le nombre à tester
|
||||
* @returns {Object} Un objet contenant l'explication en html et le booléen si oui ou non c'est un nombre d'armstrong
|
||||
* @examples armstrongNumber(153) → 153 est un nombre d'Armstrong, car 1<sup>3</sup> + 5<sup>3</sup> + 3<sup>3</sup> = 153.
|
||||
*/
|
||||
function armstrongNumber(number) {
|
||||
let numberString = number.toString();
|
||||
let numberStringLength = numberString.length;
|
||||
|
||||
let result = 0;
|
||||
let resultString = "";
|
||||
for (let index = 0; index < numberStringLength; index++) {
|
||||
result = result + parseInt(numberString[index]) ** numberStringLength;
|
||||
resultString = resultString + " + " + numberString[index] + "<sup>" + numberStringLength + "</sup>";
|
||||
}
|
||||
|
||||
const formattedNumber = formatNumberResult(number);
|
||||
const isArmstrongNumber = (result === number);
|
||||
return {
|
||||
isArmstrongNumber,
|
||||
htmlExplanation: `${formattedNumber} ${isArmstrongNumber ? "" : "n'"}est pas un nombre d'Armstrong, car ${resultString.slice(2)} = ${formatNumberResult(result)}.`
|
||||
}
|
||||
}
|
||||
|
||||
/* OUTPUTS */
|
||||
exports.armstrongNumberOutput = ({ res, next }, argsObject) => {
|
||||
let { number } = argsObject;
|
||||
|
||||
// S'il n'y a pas les champs obligatoire
|
||||
if (!(number)) {
|
||||
return errorHandling(next, requiredFields);
|
||||
}
|
||||
|
||||
// Si ce n'est pas un nombre
|
||||
number = parseInt(number);
|
||||
if (isNaN(number) || number <= 0) {
|
||||
return errorHandling(next, { message: "Veuillez rentré un nombre valide.", statusCode: 400 });
|
||||
}
|
||||
|
||||
return res.status(200).json(armstrongNumber(number));
|
||||
}
|
42
api/assets/functions/main/calculateAge.js
Normal file
42
api/assets/functions/main/calculateAge.js
Normal file
@ -0,0 +1,42 @@
|
||||
const errorHandling = require('../../utils/errorHandling');
|
||||
const moment = require('moment');
|
||||
const { requiredFields } = require('../../config/errors');
|
||||
|
||||
function calculateAge(currentDate, { birthDateDay, birthDateMonth, birthDateYear }) {
|
||||
const day = currentDate.getDate();
|
||||
const month = currentDate.getMonth();
|
||||
const currentDateMoment = moment([currentDate.getFullYear(), month, day]);
|
||||
const birthDateMoment = moment([birthDateYear, birthDateMonth - 1, birthDateDay]);
|
||||
|
||||
// Calcule l'âge - Moment.js
|
||||
const ageYears = currentDateMoment.diff(birthDateMoment, 'year');
|
||||
birthDateMoment.add(ageYears, 'years');
|
||||
const ageMonths = currentDateMoment.diff(birthDateMoment, 'months');
|
||||
birthDateMoment.add(ageMonths, 'months');
|
||||
const ageDays = currentDateMoment.diff(birthDateMoment, 'days');
|
||||
|
||||
const isBirthday = (birthDateDay === day && birthDateMonth === (month + 1));
|
||||
return { ageYears, ageMonths, ageDays, isBirthday };
|
||||
}
|
||||
|
||||
/* OUTPUTS */
|
||||
exports.calculateAgeOutput = ({ res, next }, argsObject) => {
|
||||
let { birthDateDay, birthDateMonth, birthDateYear } = argsObject;
|
||||
birthDateDay = parseInt(birthDateDay);
|
||||
birthDateMonth = parseInt(birthDateMonth);
|
||||
birthDateYear = parseInt(birthDateYear);
|
||||
|
||||
// S'il n'y a pas les champs obligatoire
|
||||
if (!(birthDateDay && birthDateMonth && birthDateYear)) {
|
||||
return errorHandling(next, requiredFields);
|
||||
}
|
||||
|
||||
// Si ce n'est pas une date valide
|
||||
const currentDate = new Date();
|
||||
const birthDate = new Date(birthDateYear, birthDateMonth - 1, birthDateDay);
|
||||
if (!(currentDate > birthDate)) {
|
||||
return errorHandling(next, { message: "Veuillez rentré une date valide...", statusCode: 400 });
|
||||
}
|
||||
|
||||
return res.status(200).json(calculateAge(currentDate, { birthDateYear, birthDateMonth, birthDateDay }));
|
||||
}
|
34
api/assets/functions/main/convertCurrency.js
Normal file
34
api/assets/functions/main/convertCurrency.js
Normal file
@ -0,0 +1,34 @@
|
||||
const axios = require('axios');
|
||||
const errorHandling = require('../../utils/errorHandling');
|
||||
const { requiredFields } = require('../../config/errors');
|
||||
|
||||
/* OUTPUTS */
|
||||
exports.convertCurrencyOutput = ({ res, next }, argsObject) => {
|
||||
let { number, baseCurrency, finalCurrency } = argsObject;
|
||||
|
||||
// S'il n'y a pas les champs obligatoire
|
||||
if (!(number && baseCurrency && finalCurrency)) {
|
||||
return errorHandling(next, requiredFields);
|
||||
}
|
||||
|
||||
// Si ce n'est pas un nombre
|
||||
number = parseFloat(number);
|
||||
if (isNaN(number)) {
|
||||
return errorHandling(next, { message: "Veuillez rentré un nombre valide.", statusCode: 400 });
|
||||
}
|
||||
|
||||
axios.get(`https://api.exchangeratesapi.io/latest?base=${baseCurrency}`)
|
||||
.then((response) => {
|
||||
const rate = response.data.rates[finalCurrency];
|
||||
if (!rate) {
|
||||
return errorHandling(next, { message: "La devise n'existe pas.", statusCode: 404 });
|
||||
}
|
||||
const result = rate * number;
|
||||
const dateObject = new Date(response.data.date);
|
||||
const year = dateObject.getFullYear();
|
||||
const day = ('0'+(dateObject.getDate())).slice(-2);
|
||||
const month = ('0'+(dateObject.getMonth()+1)).slice(-2);
|
||||
return res.status(200).json({ date: `${day}/${month}/${year}`, result });
|
||||
})
|
||||
.catch(() => errorHandling(next, { message: "La devise n'existe pas.", statusCode: 404 }));
|
||||
}
|
50
api/assets/functions/main/convertDistance.js
Normal file
50
api/assets/functions/main/convertDistance.js
Normal file
@ -0,0 +1,50 @@
|
||||
const errorHandling = require('../../utils/errorHandling');
|
||||
const { requiredFields, generalError } = require('../../config/errors');
|
||||
|
||||
const correspondancesDistance = ["pm", null, null, "nm", null, null, "µm", null, null, "mm", "cm", "dm", "m", "dam", "hm", "km", null, null, "Mm", null, null, "Gm", null, null, "Tm"];
|
||||
|
||||
/**
|
||||
* @description Convertis la longueur (distance) avec les unités allant de picomètre au Téramètre.
|
||||
* @requires {@link correspondancesDistance}
|
||||
* @param {Number} firstValue - Le nombre que vous voulez convertir
|
||||
* @param {String} unitFirstValue - L'unité du nombre que vous voulez convertir
|
||||
* @param {String} unitFinalValue - L'unité de votre nombre après la conversion
|
||||
* @returns {Object|Boolean} → false si arguments non valides et sinon un objet contenant la string et le nombre résultat
|
||||
* @examples convertDistance(500, 'cm', 'm') → { resultNumber: 5, resultString: "5 m" }
|
||||
*/
|
||||
function convertDistance(firstValue, unitFirstValue, unitFinalValue) {
|
||||
const index1 = correspondancesDistance.indexOf(unitFirstValue);
|
||||
const index2 = correspondancesDistance.indexOf(unitFinalValue);
|
||||
if (index1 !== -1 && index2 !== -1) {
|
||||
const difference = index1 - index2;
|
||||
const result = firstValue * Math.pow(10, difference);
|
||||
return {
|
||||
resultNumber: result,
|
||||
resultString: `${result} ${unitFinalValue}`
|
||||
};
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* OUTPUTS */
|
||||
exports.convertDistanceOutput = ({ res, next }, argsObject) => {
|
||||
let { number, numberUnit, finalUnit } = argsObject;
|
||||
|
||||
// S'il n'y a pas les champs obligatoire
|
||||
if (!(number && numberUnit && finalUnit)) {
|
||||
return errorHandling(next, requiredFields);
|
||||
}
|
||||
|
||||
// Si ce n'est pas un nombre
|
||||
number = parseInt(number);
|
||||
if (isNaN(number)) {
|
||||
return errorHandling(next, { message: "Veuillez rentré un nombre valide.", statusCode: 400 });
|
||||
}
|
||||
|
||||
const result = convertDistance(number, numberUnit, finalUnit);
|
||||
if (!result) {
|
||||
return errorHandling(next, generalError);
|
||||
}
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
243
api/assets/functions/main/convertEncoding.js
Normal file
243
api/assets/functions/main/convertEncoding.js
Normal file
@ -0,0 +1,243 @@
|
||||
const errorHandling = require('../../utils/errorHandling');
|
||||
const { requiredFields, generalError } = require('../../config/errors');
|
||||
|
||||
/**
|
||||
* @description Convertis un nombre décimal en binaire.
|
||||
* @param {String} value - Le nombre à convertir en string
|
||||
* @returns {String} - Le nombre en binaire
|
||||
* @examples decimalToBinary('2') → '10'
|
||||
*/
|
||||
function decimalToBinary(value) {
|
||||
value = Number(value);
|
||||
if (isNaN(value)) {
|
||||
return false;
|
||||
} else {
|
||||
return value.toString(2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convertis un nombre binaire en décimal.
|
||||
* @param {String} value - Le nombre à convertir
|
||||
* @returns {(Number|String)} - Le nombre en décimal soit en nombre ou soit en string si supérieur à 1000 car pour 1000 par exemple formatNumberResult renvoie '1 000'
|
||||
* @examples binaryToDecimal('10') → 2
|
||||
*/
|
||||
function binaryToDecimal(value) {
|
||||
const result = parseInt(Number(value), 2);
|
||||
if (isNaN(result)) {
|
||||
return false;
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convertis un nombre décimal en hexadécimal.
|
||||
* @param {String} value - Le nombre à convertir
|
||||
* @returns {String} - Le nombre en hexadécimal
|
||||
* @examples decimalToHexadecimal('15') → 'F'
|
||||
*/
|
||||
function decimalToHexadecimal(value) {
|
||||
value = Number(value);
|
||||
if (isNaN(value)) {
|
||||
return false;
|
||||
} else {
|
||||
return value.toString(16).toUpperCase();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convertis un nombre hexadécimal en décimal.
|
||||
* @param {String} value - Le nombre à convertir
|
||||
* @returns {(Number|String)} - Le nombre en décimal soit en nombre ou soit en string si supérieur à 1000 car pour 1000 par exemple formatNumberResult renvoie '1 000'
|
||||
* @examples hexadecimalToDecimal('F') → 15
|
||||
*/
|
||||
function hexadecimalToDecimal(value) {
|
||||
const result = parseInt(value, 16);
|
||||
if (isNaN(result)) {
|
||||
return false;
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convertis un nombre binaire en hexadécimal.
|
||||
* @param {String} value - Le nombre à convertir
|
||||
* @returns {String} - Le nombre en hexadécimal
|
||||
* @examples binaryToHexadecimal('1111') → 'F'
|
||||
*/
|
||||
function binaryToHexadecimal(value) {
|
||||
value = Number(value);
|
||||
value = parseInt(value, 2);
|
||||
if (isNaN(value)) {
|
||||
return false;
|
||||
} else {
|
||||
return parseInt(value).toString(16).toUpperCase();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convertis un nombre hexadécimal en binaire.
|
||||
* @param {String} value - Le nombre à convertir
|
||||
* @returns {String} - Le nombre en binaire
|
||||
* @examples hexadecimalToBinary('F') → '1111'
|
||||
*/
|
||||
function hexadecimalToBinary(value) {
|
||||
value = parseInt(value, 16);
|
||||
if (isNaN(value)) {
|
||||
return false;
|
||||
} else {
|
||||
return parseInt(value).toString(2);
|
||||
}
|
||||
}
|
||||
|
||||
// Convertis des nombres de différentes bases et convertis en UTF-8. (source : http://jsfiddle.net/47zwb41o)
|
||||
|
||||
/**
|
||||
* @description Convertis chaque caractère d'une string en codePoint Unicode.
|
||||
* @param {String} value - La chaîne de caractère à convertir
|
||||
* @returns {String}
|
||||
* @examples textToNumberUnicode('abc') → '97 98 99'
|
||||
*/
|
||||
function textToNumberUnicode(string) {
|
||||
try {
|
||||
let resultat = "";
|
||||
for (let index in string) {
|
||||
resultat = resultat + string.codePointAt(index) + " ";
|
||||
}
|
||||
return resultat;
|
||||
}
|
||||
catch(error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convertis chaque codePoint Unicode en caractère.
|
||||
* @param {String} string - Nombre Unicode à convertir espacé par un espace à chaque fois
|
||||
* @returns {String}
|
||||
* @examples numberUnicodeToText('97 98 99') → 'abc'
|
||||
*/
|
||||
function numberUnicodeToText(string) {
|
||||
try {
|
||||
const array = string.split(" ");
|
||||
let resultat = "";
|
||||
for (let index in array) {
|
||||
resultat = resultat + String.fromCodePoint(parseInt(array[index]).toString());
|
||||
}
|
||||
return resultat;
|
||||
}
|
||||
catch(error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convertis un Texte en Binaire (UTF-8).
|
||||
* @param {String} s - La chaîne de caractère à convertir
|
||||
* @returns {String}
|
||||
* @examples textToBinary('abc') → '01100001 01100010 01100011'
|
||||
*/
|
||||
function textToBinary(s) {
|
||||
try {
|
||||
s = unescape( encodeURIComponent(s));
|
||||
let chr, i = 0, l = s.length, out = '';
|
||||
for( ; i < l; i ++ ){
|
||||
chr = s.charCodeAt( i ).toString(2);
|
||||
while(chr.length % 8 != 0 ){ chr = '0' + chr; }
|
||||
out += chr;
|
||||
}
|
||||
return out.replace(/(\d{8})/g, '$1 ').replace(/(^\s+|\s+$)/,'');
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convertis du Binaire (UTF-8) en Texte.
|
||||
* @param {String} s - La chaîne de caractère contenant tous les octets à convertir
|
||||
* @returns {String}
|
||||
* @examples binaryToText('01100001 01100010 01100011') → 'abc'
|
||||
*/
|
||||
function binaryToText(s){
|
||||
try {
|
||||
s = s.replace(/\s/g,'')
|
||||
let i = 0, l = s.length, chr, out = '';
|
||||
for( ; i < l; i += 8){
|
||||
chr = parseInt( s.substr(i, 8 ), 2).toString(16);
|
||||
out += '%' + ((chr.length % 2 == 0) ? chr : '0' + chr);
|
||||
}
|
||||
return decodeURIComponent(out);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convertis un Texte en Hexadécimal (UTF-8).
|
||||
* @param {String} s - La chaîne de caractère à convertir
|
||||
* @returns {String}
|
||||
* @examples textToHexadecimal('abc') → '61 62 63'
|
||||
*/
|
||||
function textToHexadecimal (s) {
|
||||
try {
|
||||
s = unescape( encodeURIComponent( s ) );
|
||||
let chr, i = 0, l = s.length, out = '';
|
||||
for( ; i < l; i++ ){
|
||||
chr = s.charCodeAt( i ).toString( 16 );
|
||||
out += ( chr.length % 2 == 0 ) ? chr : '0' + chr;
|
||||
out += " ";
|
||||
}
|
||||
return out.toUpperCase();
|
||||
}
|
||||
catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convertis de l'Hexadécimal (UTF-8) en Texte.
|
||||
* @param {String} s - La chaîne de caractère contenant tous les nombres Hexadécimal à convertir
|
||||
* @returns {String}
|
||||
* @examples hexadecimalToText('61 62 63') → 'abc'
|
||||
*/
|
||||
function hexadecimalToText (s) {
|
||||
try {
|
||||
s = s.replace(/\s/g,'');
|
||||
return decodeURIComponent( s.replace( /../g, '%$&' ) );
|
||||
}
|
||||
catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/* OUTPUTS */
|
||||
const convertEncoding = { decimalToBinary, binaryToDecimal, decimalToHexadecimal, hexadecimalToDecimal, binaryToHexadecimal, hexadecimalToBinary, textToNumberUnicode, numberUnicodeToText, textToBinary, binaryToText, textToHexadecimal, hexadecimalToText };
|
||||
|
||||
function executeFunction(option, value) {
|
||||
return convertEncoding[option](value);
|
||||
}
|
||||
|
||||
exports.convertEncodingOutput = ({ res, next }, argsObject) => {
|
||||
let { value, functionName } = argsObject;
|
||||
|
||||
// S'il n'y a pas les champs obligatoire
|
||||
if (!(value && functionName)) {
|
||||
return errorHandling(next, requiredFields);
|
||||
}
|
||||
|
||||
// Si la fonction de convertEncoding n'existe pas
|
||||
if (!convertEncoding.hasOwnProperty(functionName)) {
|
||||
return errorHandling(next, { message: "Cette conversion de convertEncoding n'existe pas." });
|
||||
}
|
||||
|
||||
const result = executeFunction(functionName, value);
|
||||
|
||||
// Mauvaise valeur entrée
|
||||
if (!result) {
|
||||
return errorHandling(next, generalError);
|
||||
}
|
||||
|
||||
return res.status(200).json({ result });
|
||||
}
|
109
api/assets/functions/main/convertRomanArabicNumbers.js
Normal file
109
api/assets/functions/main/convertRomanArabicNumbers.js
Normal file
@ -0,0 +1,109 @@
|
||||
const errorHandling = require('../../utils/errorHandling');
|
||||
const { requiredFields, generalError } = require('../../config/errors');
|
||||
|
||||
/* Variable pour convertRomanArabicNumbers */
|
||||
const correspondancesRomainArabe = [
|
||||
[1000, "M"],
|
||||
[900, "CM"],
|
||||
[500, "D"],
|
||||
[400, "CD"],
|
||||
[100, "C"],
|
||||
[90, "XC"],
|
||||
[50, "L"],
|
||||
[40, "XL"],
|
||||
[10, "X"],
|
||||
[9, "IX"],
|
||||
[5, "V"],
|
||||
[4, "IV"],
|
||||
[1, "I"],
|
||||
];
|
||||
|
||||
/**
|
||||
* @description Convertis un nombre arabe en nombre romain.
|
||||
* @requires {@link correspondancesRomainArabe}
|
||||
* @param {Number} nombre - Le nombre arabe à convertir
|
||||
* @returns {String}
|
||||
* @examples convertArabicToRoman(24) → 'XXIV'
|
||||
*/
|
||||
function convertArabicToRoman(nombre) {
|
||||
// Initialisation de la variable qui va contenir le résultat de la conversion
|
||||
let chiffresRomains = "";
|
||||
|
||||
function extraireChiffreRomain(valeurLettre, lettres) {
|
||||
while (nombre >= valeurLettre) {
|
||||
chiffresRomains = chiffresRomains + lettres;
|
||||
nombre = nombre - valeurLettre;
|
||||
}
|
||||
}
|
||||
|
||||
correspondancesRomainArabe.forEach(correspondance => {
|
||||
extraireChiffreRomain(correspondance[0], correspondance[1]);
|
||||
});
|
||||
|
||||
return chiffresRomains;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Convertis un nombre romain en nombre arabe.
|
||||
* @requires {@link correspondancesRomainArabe}
|
||||
* @param {String} str - Le nombre romain à convertir
|
||||
* @returns {Number}
|
||||
* @examples convertRomanToArabic('XXIV') → 24
|
||||
*/
|
||||
function convertRomanToArabic(str) {
|
||||
let result = 0;
|
||||
for (let i = 0;i < correspondancesRomainArabe.length; i++) {
|
||||
while (str.indexOf(correspondancesRomainArabe[i][1]) === 0) {
|
||||
// Ajout de la valeur décimale au résultat
|
||||
result += correspondancesRomainArabe[i][0];
|
||||
// Supprimer la lettre romaine correspondante du début
|
||||
str = str.replace(correspondancesRomainArabe[i][1],'');
|
||||
}
|
||||
}
|
||||
if (str != '') {
|
||||
result = 0;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/* OUTPUTS */
|
||||
exports.convertRomanToArabicOutput = ({ res, next }, argsObject) => {
|
||||
let { romanNumber } = argsObject;
|
||||
|
||||
// S'il n'y a pas les champs obligatoire
|
||||
if (!(romanNumber)) {
|
||||
return errorHandling(next, requiredFields);
|
||||
}
|
||||
|
||||
// Formate le paramètre
|
||||
try {
|
||||
romanNumber = romanNumber.toUpperCase();
|
||||
}
|
||||
catch {
|
||||
return errorHandling(next, generalError);
|
||||
}
|
||||
|
||||
const result = convertRomanToArabic(romanNumber);
|
||||
if (result === 0) {
|
||||
return errorHandling(next, generalError);
|
||||
}
|
||||
|
||||
return res.status(200).json({ result });
|
||||
}
|
||||
|
||||
exports.convertArabicToRomanOutput = ({ res, next }, argsObject) => {
|
||||
let { number } = argsObject;
|
||||
|
||||
// S'il n'y a pas les champs obligatoire
|
||||
if (!(number)) {
|
||||
return errorHandling(next, requiredFields);
|
||||
}
|
||||
|
||||
// Si ce n'est pas un nombre
|
||||
number = parseInt(number);
|
||||
if (isNaN(number)) {
|
||||
return errorHandling(next, { message: "Veuillez rentré un nombre valide.", statusCode: 400 });
|
||||
}
|
||||
|
||||
return res.status(200).json({ result: convertArabicToRoman(number) });
|
||||
}
|
52
api/assets/functions/main/convertTemperature.js
Normal file
52
api/assets/functions/main/convertTemperature.js
Normal file
@ -0,0 +1,52 @@
|
||||
const errorHandling = require('../../utils/errorHandling');
|
||||
const { requiredFields, generalError } = require('../../config/errors');
|
||||
|
||||
/**
|
||||
* @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)
|
||||
* @returns {Object} false si arguments non valides et sinon un objet contenant la string et le nombre résultat
|
||||
* @examples convertTemperature(23, '°C') → { resultNumber: 73.4, resultString: "73.4 °F" }
|
||||
*/
|
||||
function convertTemperature(degree, unit) {
|
||||
let temperatureValue = 0;
|
||||
let temperatureUnit;
|
||||
if (unit === "°C") {
|
||||
temperatureUnit = "°F";
|
||||
temperatureValue = ((degree * 9/5) + 32);
|
||||
}
|
||||
else if (unit === "°F") {
|
||||
temperatureUnit = "°C";
|
||||
temperatureValue = (degree - 32) * 5/9;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
return {
|
||||
resultNumber: temperatureValue,
|
||||
resultString: `${temperatureValue} ${temperatureUnit}`
|
||||
};
|
||||
}
|
||||
|
||||
/* OUTPUTS */
|
||||
exports.convertTemperatureOutput = ({ res, next }, argsObject) => {
|
||||
let { degree, unit } = argsObject;
|
||||
|
||||
// S'il n'y a pas les champs obligatoire
|
||||
if (!(degree && unit)) {
|
||||
return errorHandling(next, requiredFields);
|
||||
}
|
||||
|
||||
// Si ce n'est pas un nombre
|
||||
degree = parseInt(degree);
|
||||
if (isNaN(degree)) {
|
||||
return errorHandling(next, { message: "Veuillez rentré un nombre valide.", statusCode: 400 });
|
||||
}
|
||||
|
||||
const result = convertTemperature(degree, unit);
|
||||
if (!result) {
|
||||
return errorHandling(next, generalError);
|
||||
}
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
46
api/assets/functions/main/heapAlgorithm.js
Normal file
46
api/assets/functions/main/heapAlgorithm.js
Normal file
@ -0,0 +1,46 @@
|
||||
const errorHandling = require('../../utils/errorHandling');
|
||||
const { requiredFields } = require('../../config/errors');
|
||||
|
||||
/**
|
||||
* @description Retourne un tableau contenant toutes les possibilités d'anagramme d'un mot.
|
||||
* @param {String} string - La chaîne de caractère à permuter
|
||||
* @returns {Array}
|
||||
* @examples heapAlgorithm('abc') → ["abc", "acb", "bac", "bca", "cab", "cba"]
|
||||
*/
|
||||
function heapAlgorithm(string) {
|
||||
let results = [];
|
||||
|
||||
if (string.length === 1) {
|
||||
results.push(string);
|
||||
return results;
|
||||
}
|
||||
|
||||
for (let indexString = 0; indexString < string.length; indexString++) {
|
||||
const firstChar = string[indexString];
|
||||
const charsLeft = string.substring(0, indexString) + string.substring(indexString + 1);
|
||||
const innerPermutations = heapAlgorithm(charsLeft);
|
||||
for (let indexPermutation = 0; indexPermutation < innerPermutations.length; indexPermutation++) {
|
||||
results.push(firstChar + innerPermutations[indexPermutation]);
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/* OUTPUTS */
|
||||
exports.heapAlgorithmOutput = ({ res, next }, argsObject) => {
|
||||
let { string } = argsObject;
|
||||
|
||||
// S'il n'y a pas les champs obligatoire
|
||||
if (!(string)) {
|
||||
return errorHandling(next, requiredFields);
|
||||
}
|
||||
|
||||
// Si la chaîne de caractère dépasse LIMIT_CHARACTERS caractères
|
||||
const LIMIT_CHARACTERS = 8;
|
||||
if (string.length > LIMIT_CHARACTERS) {
|
||||
return errorHandling(next, { message: `Par souci de performance, vous ne pouvez pas exécuter cette fonction avec un mot dépassant ${LIMIT_CHARACTERS} caractères.`, statusCode: 400 });
|
||||
}
|
||||
|
||||
const result = heapAlgorithm(string);
|
||||
return res.status(200).json(result);
|
||||
}
|
32
api/assets/functions/main/randomNumber.js
Normal file
32
api/assets/functions/main/randomNumber.js
Normal file
@ -0,0 +1,32 @@
|
||||
const errorHandling = require('../../utils/errorHandling');
|
||||
const { requiredFields } = require('../../config/errors');
|
||||
|
||||
/**
|
||||
* @description Génère un nombre aléatoire entre un minimum inclus et un maximum inclus.
|
||||
* @param {Number} min Nombre Minimum
|
||||
* @param {Number} max Nombre Maximum
|
||||
* @returns {Number} Nombre aléatoire
|
||||
* @examples randomNumber(1, 2) → retourne soit 1 ou 2
|
||||
*/
|
||||
function randomNumber(min, max) {
|
||||
return Math.floor(Math.random() * (max - min +1)) + min;
|
||||
}
|
||||
|
||||
/* OUTPUTS */
|
||||
exports.randomNumberOutput = ({ res, next }, argsObject) => {
|
||||
let { min, max } = argsObject;
|
||||
|
||||
// S'il n'y a pas les champs obligatoire
|
||||
if (!(min && max)) {
|
||||
return errorHandling(next, requiredFields);
|
||||
}
|
||||
|
||||
// Si ce ne sont pas des nombres
|
||||
min = parseInt(min);
|
||||
max = parseInt(max);
|
||||
if (isNaN(min) || isNaN(max)) {
|
||||
return errorHandling(next, { message: "Les paramètres min et max doivent être des nombres...", statusCode: 400 });
|
||||
}
|
||||
|
||||
return res.status(200).json({ result: randomNumber(min, max) });
|
||||
}
|
37
api/assets/functions/main/weatherRequest.js
Normal file
37
api/assets/functions/main/weatherRequest.js
Normal file
@ -0,0 +1,37 @@
|
||||
const axios = require('axios');
|
||||
const Queue = require('smart-request-balancer');
|
||||
const errorHandling = require('../../utils/errorHandling');
|
||||
const { requiredFields } = require('../../config/errors');
|
||||
const { WEATHER_API_KEY } = require('../../config/config');
|
||||
|
||||
const queue = new Queue({
|
||||
/*
|
||||
rate: number of requests
|
||||
per
|
||||
limit: number of seconds
|
||||
*/
|
||||
rules: {
|
||||
weatherRequest: {
|
||||
rate: 50,
|
||||
limit: 60,
|
||||
priority: 1
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
/* OUTPUTS */
|
||||
exports.weatherRequestOutput = async ({ res, next }, argsObject) => {
|
||||
let { cityName } = argsObject;
|
||||
|
||||
// S'il n'y a pas les champs obligatoire
|
||||
if (!(cityName)) {
|
||||
return errorHandling(next, requiredFields);
|
||||
}
|
||||
|
||||
// Récupère les données météo grâce à l'API : openweathermap.org. (→ avec limite de 50 requêtes par minute)
|
||||
queue.request(() => {
|
||||
axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&lang=fr&units=metric&appid=${WEATHER_API_KEY}`)
|
||||
.then((response) => res.status(200).json(response.data))
|
||||
.catch(() => errorHandling(next, { message: "La ville n'existe pas (dans l'API de openweathermap.org).", statusCode: 404 }));
|
||||
}, 'everyone', 'weatherRequest');
|
||||
}
|
14
api/assets/functions/secondary/formatNumberResult.js
Normal file
14
api/assets/functions/secondary/formatNumberResult.js
Normal file
@ -0,0 +1,14 @@
|
||||
/**
|
||||
* @description Formate un nombre avec des espaces.
|
||||
* @param {Number} number
|
||||
* @param {String} separator Le séparateur utilisé pour la virgule (exemple: "." ou ",")
|
||||
* @returns {String} - Le nombre formaté
|
||||
* @examples formatNumberResult(76120) → '76 120'
|
||||
*/
|
||||
function formatNumberResult(number, separator = ".") {
|
||||
let parts = number.toString().split(separator);
|
||||
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
|
||||
return parts.join(separator);
|
||||
}
|
||||
|
||||
module.exports = formatNumberResult;
|
BIN
api/assets/images/functions/calculateAge.png
Normal file
BIN
api/assets/images/functions/calculateAge.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 16 KiB |
BIN
api/assets/images/functions/convertCurrency.png
Normal file
BIN
api/assets/images/functions/convertCurrency.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 12 KiB |
BIN
api/assets/images/functions/randomNumber.png
Normal file
BIN
api/assets/images/functions/randomNumber.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 10 KiB |
BIN
api/assets/images/functions/weatherRequest.png
Normal file
BIN
api/assets/images/functions/weatherRequest.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 16 KiB |
9
api/assets/utils/database.js
Normal file
9
api/assets/utils/database.js
Normal file
@ -0,0 +1,9 @@
|
||||
const Sequelize = require('sequelize');
|
||||
const { DATABASE } = require('../config/config');
|
||||
|
||||
const sequelize = new Sequelize(DATABASE.name, DATABASE.user, DATABASE.password, {
|
||||
dialect: 'mysql',
|
||||
host: DATABASE.host
|
||||
});
|
||||
|
||||
module.exports = sequelize;
|
7
api/assets/utils/errorHandling.js
Normal file
7
api/assets/utils/errorHandling.js
Normal file
@ -0,0 +1,7 @@
|
||||
function errorHandling(next, { statusCode, message }) {
|
||||
const error = new Error(message);
|
||||
error.statusCode = statusCode;
|
||||
next(error);
|
||||
}
|
||||
|
||||
module.exports = errorHandling;
|
Reference in New Issue
Block a user