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

56 lines
1.5 KiB
JavaScript
Raw 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')
/**
* @description Calcule les counter premiers nombres de la suite de fibonacci.
2020-08-03 12:04:07 +02:00
* @param {number} counter
*/
2020-08-03 12:04:07 +02:00
function fibonacci (counter, result = [], a = 0, b = 1) {
if (counter === 0) {
return result
}
counter--
result.push(a)
return fibonacci(counter, result, b, a + b)
}
/* OUTPUTS */
2020-08-03 12:04:07 +02:00
module.exports = ({ res, next }, argsObject) => {
let { counter } = argsObject
2020-08-03 12:04:07 +02:00
// S'il n'y a pas les champs obligatoire
2020-08-03 14:14:45 +02:00
if (!counter) {
2020-08-03 12:04:07 +02:00
return errorHandling(next, requiredFields)
}
2020-08-03 12:04:07 +02:00
// Si ce n'est pas un nombre
counter = parseInt(counter)
if (isNaN(counter)) {
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
}
// Si le nombre dépasse LIMIT_COUNTER
const LIMIT_COUNTER = 51
if (counter >= LIMIT_COUNTER) {
2020-08-03 14:14:45 +02:00
return errorHandling(next, {
message: `Par souci de performance, vous ne pouvez pas exécuter cette fonction avec un compteur dépassant ${LIMIT_COUNTER -
1}.`,
statusCode: 400
})
2020-08-03 12:04:07 +02:00
}
const result = fibonacci(counter)
2020-08-03 14:14:45 +02:00
const resultFormatted = result.map(number => formatNumberResult(number))
2020-08-03 12:04:07 +02:00
return res.status(200).json({
result,
resultFormatted,
2020-08-03 14:14:45 +02:00
resultHTML: `<p>Les ${counter} premiers nombres de la suite de fibonacci :<br/> ${resultFormatted.join(
', '
)}</p>`
2020-08-03 12:04:07 +02:00
})
}