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/randomNumber.js

48 lines
1.3 KiB
JavaScript
Raw Permalink Normal View History

2020-08-03 12:04:07 +02:00
const errorHandling = require('../../utils/errorHandling')
const { requiredFields } = require('../../config/errors')
const formatNumberResult = require('../secondary/formatNumberResult')
2020-08-03 12:04:07 +02:00
/**
* @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
2020-08-03 12:04:07 +02:00
*/
function randomNumber (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
/* OUTPUTS */
2020-04-27 22:06:37 +02:00
const randomNumberOutput = ({ res, next }, argsObject) => {
2020-08-03 12:04:07 +02:00
let { min, max } = argsObject
2020-08-03 12:04:07 +02:00
// 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)) {
2020-08-03 14:14:45 +02:00
return errorHandling(next, {
message: 'Les paramètres min et max doivent être des nombres...',
statusCode: 400
})
2020-08-03 12:04:07 +02:00
}
const result = randomNumber(min, max)
2020-08-03 14:14:45 +02:00
return res
.status(200)
.json({
result,
resultHTML: `<p>Nombre aléatoire compris entre ${min} inclus et ${max} inclus : <strong>${formatNumberResult(
result
)}</strong></p>`
})
2020-04-27 22:06:37 +02:00
}
2020-08-03 12:04:07 +02:00
exports.randomNumber = randomNumber
exports.randomNumberOutput = randomNumberOutput