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

59 lines
1.6 KiB
JavaScript
Raw Normal View History

2020-08-03 12:04:07 +02:00
const errorHandling = require('../../utils/errorHandling')
const { requiredFields } = require('../../config/errors')
/**
* @description Inverse la chaîne de caractère
2020-08-03 12:04:07 +02:00
* @param {string} string
* @returns {string}
* @example reverseString('Hello') 'olleH'
*/
2020-08-03 12:04:07 +02:00
function reverseString (string) {
2020-08-03 14:14:45 +02:00
return string
.split('')
.reverse()
.join('')
}
/**
* @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
* @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
}
/* OUTPUTS */
2020-08-03 12:04:07 +02:00
module.exports = ({ res, next }, argsObject) => {
let { string } = 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 (!string) {
2020-08-03 12:04:07 +02:00
return errorHandling(next, requiredFields)
}
2020-08-03 12:04:07 +02:00
if (typeof string !== 'string') {
2020-08-03 14:14:45 +02:00
return errorHandling(next, {
message: 'Vous devez rentré une chaîne de caractère valide.',
statusCode: 400
})
2020-08-03 12:04:07 +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,
2020-08-03 14:14:45 +02:00
resultHTML: `<p>"${string}" ${
isPalindromeResult ? 'est' : "n'est pas"
} un palindrome car <br/> "${string}" ${
isPalindromeResult ? '===' : '!=='
} "${reverseStringResult}"</p>`
2020-08-03 12:04:07 +02:00
})
}