2020-08-03 12:04:07 +02:00
|
|
|
const errorHandling = require('../../utils/errorHandling')
|
|
|
|
const { requiredFields } = require('../../config/errors')
|
|
|
|
const formatNumberResult = require('../secondary/formatNumberResult')
|
2020-03-17 18:35:03 +01:00
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
/**
|
2020-03-17 18:35:03 +01:00
|
|
|
* @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.
|
2020-08-03 12:04:07 +02:00
|
|
|
*/
|
|
|
|
function armstrongNumber (number) {
|
|
|
|
const numberString = number.toString()
|
|
|
|
const numberStringLength = numberString.length
|
2020-03-17 18:35:03 +01:00
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
let result = 0
|
|
|
|
let resultString = ''
|
|
|
|
for (let index = 0; index < numberStringLength; index++) {
|
|
|
|
result = result + parseInt(numberString[index]) ** numberStringLength
|
2020-08-03 14:14:45 +02:00
|
|
|
resultString =
|
|
|
|
resultString +
|
|
|
|
' + ' +
|
|
|
|
numberString[index] +
|
|
|
|
'<sup>' +
|
|
|
|
numberStringLength +
|
|
|
|
'</sup>'
|
2020-08-03 12:04:07 +02:00
|
|
|
}
|
2020-03-17 18:35:03 +01:00
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
const formattedNumber = formatNumberResult(number)
|
2020-08-03 14:14:45 +02:00
|
|
|
const isArmstrongNumber = result === number
|
2020-08-03 12:04:07 +02:00
|
|
|
return {
|
|
|
|
isArmstrongNumber,
|
2020-08-03 14:14:45 +02:00
|
|
|
resultHTML: `<p>${formattedNumber} ${
|
|
|
|
isArmstrongNumber ? 'est' : "n'est pas"
|
|
|
|
} un nombre d'Armstrong, car ${resultString.slice(
|
|
|
|
2
|
|
|
|
)} = ${formatNumberResult(result)}.</p>`
|
2020-08-03 12:04:07 +02:00
|
|
|
}
|
2020-03-17 18:35:03 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/* OUTPUTS */
|
2020-08-03 12:04:07 +02:00
|
|
|
module.exports = ({ res, next }, argsObject) => {
|
|
|
|
let { number } = argsObject
|
2020-03-24 16:11:55 +01:00
|
|
|
|
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 (!number) {
|
2020-08-03 12:04:07 +02:00
|
|
|
return errorHandling(next, requiredFields)
|
|
|
|
}
|
2020-03-17 18:35:03 +01:00
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
// Si ce n'est pas un nombre
|
|
|
|
number = parseInt(number)
|
|
|
|
if (isNaN(number) || number <= 0) {
|
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
|
|
|
}
|
|
|
|
|
|
|
|
return res.status(200).json(armstrongNumber(number))
|
|
|
|
}
|