2020-08-03 12:04:07 +02:00
const errorHandling = require ( '../../utils/errorHandling' )
const { requiredFields } = require ( '../../config/errors' )
2020-05-07 11:36:22 +02:00
/ * *
* @ description Inverse la chaîne de caractère
2020-08-03 12:04:07 +02:00
* @ param { string } string
2020-05-07 11:36:22 +02:00
* @ returns { string }
* @ example reverseString ( 'Hello' ) → 'olleH'
* /
2020-08-03 12:04:07 +02:00
function reverseString ( string ) {
return string . split ( '' ) . reverse ( ) . join ( '' )
2020-05-07 11:36:22 +02:00
}
/ * *
* @ description Vérifie si un mot est un palindrome ( un mot qui peut s ' écrire dans les deux sens )
* @ requires reverseString
2020-08-03 12:04:07 +02:00
* @ param { string } string
2020-05-07 11:36:22 +02:00
* @ param { string } reverseStringResult La chaîne de caractères inversée
* @ returns { boolean }
* @ example isPalindrome ( 'kayak' ) → true
* /
2020-08-03 12:04:07 +02:00
function isPalindrome ( string , reverseStringResult ) {
return string === reverseStringResult
2020-05-07 11:36:22 +02:00
}
/* OUTPUTS */
2020-08-03 12:04:07 +02:00
module . exports = ( { res , next } , argsObject ) => {
let { string } = argsObject
2020-05-07 11:36:22 +02:00
2020-08-03 12:04:07 +02:00
// S'il n'y a pas les champs obligatoire
if ( ! ( string ) ) {
return errorHandling ( next , requiredFields )
}
2020-05-07 11:36:22 +02:00
2020-08-03 12:04:07 +02:00
if ( typeof string !== 'string' ) {
return errorHandling ( next , { message : 'Vous devez rentré une chaîne de caractère valide.' , statusCode : 400 } )
}
2020-05-07 11:36:22 +02:00
2020-08-03 12:04:07 +02:00
string = string . toLowerCase ( )
const reverseStringResult = reverseString ( string )
const isPalindromeResult = isPalindrome ( string , reverseStringResult )
return res . status ( 200 ) . json ( {
isPalindrome : isPalindromeResult ,
reverseString : reverseStringResult ,
resultHTML : ` <p>" ${ string } " ${ ( isPalindromeResult ) ? 'est' : "n'est pas" } un palindrome car <br/> " ${ string } " ${ ( isPalindromeResult ) ? '===' : '!==' } " ${ reverseStringResult } "</p> `
} )
}