FunctionProject/scripts/fonctions_principales.js

381 lines
14 KiB
JavaScript
Raw Normal View History

/* Fonctions Principales */
2019-08-16 12:05:56 +02:00
// Affiche la météo et l'heure local selon la ville.
function weatherRequest() {
$.ajax({
url: '/php/getWeatherJson.php',
type: "POST",
success: function(data) {
try {
2019-10-18 09:55:35 +02:00
const json = jQuery.parseJSON(data);
const city = json.name;
const showDateTimeValue = timeZone(json);
$('.results').html(`🌎 Position : <a href='https://www.google.com/maps/search/?api=1&query=${json.coord.lat},${json.coord.lon}' class="yellow-color" target="_blank">${city}, ${json.sys.country}</a><br>⏰ Date et heure : ${showDateTimeValue}<br>☁️ Météo : ${capitalize(json.weather[0].description)}<br> 🌡️ Température : ${json.main.temp} °C<br> 💧 Humidité : ${json.main.humidity}% <br> <img src="https://openweathermap.org/img/wn/${json.weather[0].icon}@2x.png"/>`);
2019-08-16 12:05:56 +02:00
}
catch(error) {
$('.results').html("La ville que vous avez rentré n'existe pas (dans l'API).");
2019-08-16 12:05:56 +02:00
}
}
});
}
// Génère un nombre aléatoire entre un minimum inclus et un maximum inclus
2019-08-18 20:06:06 +02:00
function randomNumber(min, max) {
2019-10-04 20:10:38 +02:00
if (!isNaN(min) && !isNaN(max))
2019-08-16 12:05:56 +02:00
{
2019-10-04 20:10:38 +02:00
min = Math.ceil(min);
max = Math.floor(max);
2019-09-13 14:39:29 +02:00
return Math.floor(Math.random() * (max - min +1)) + min;
2019-08-16 12:05:56 +02:00
}
2019-09-13 14:39:29 +02:00
else {
2019-10-04 20:10:38 +02:00
return messageError;
2019-08-16 12:05:56 +02:00
}
}
// Calcule l'âge de quelqu'un selon la date de naissance
2019-08-18 20:06:06 +02:00
function calculateAge(birthDateEntered) {
// Les variables de la fonction
2019-10-18 09:55:35 +02:00
const birthDateDay = parseInt(birthDateEntered.substring(0, 2));
const birthDateMonth = parseInt((birthDateEntered.substring(3, 5)) - 1);
const birthDateYear = parseInt(birthDateEntered.substring(6, 10));
2019-08-18 20:06:06 +02:00
dateTimeUTC('0');
2019-10-13 20:58:13 +02:00
day = parseInt(day);
2019-08-18 20:06:06 +02:00
month = parseInt(month - 1);
year = parseInt(year);
2019-08-16 12:05:56 +02:00
2019-08-18 20:06:06 +02:00
let dateNow = moment([year, month, day]);
let birthDate = moment([birthDateYear, birthDateMonth, birthDateDay]);
2019-08-16 12:05:56 +02:00
2019-08-18 20:06:06 +02:00
// Calcule l'âge - Moment.js
let ageYears = dateNow.diff(birthDate, 'year');
birthDate.add(ageYears, 'years');
let ageMonths = dateNow.diff(birthDate, 'months');
birthDate.add(ageMonths, 'months');
let ageDays = dateNow.diff(birthDate, 'days');
2019-10-18 09:55:35 +02:00
const isValidDateFunction = isValidDate(birthDateDay + '/' + birthDateMonth + '/' + birthDateYear);
2019-09-18 18:36:18 +02:00
2019-08-18 20:06:06 +02:00
// Vérifie si la valeur entrée correspond à une date de naissance valide
2019-10-13 20:58:13 +02:00
if(isValidDateFunction === true && !isNaN(ageDays))
2019-08-18 20:06:06 +02:00
{
ageYears = formatNumberResult(ageYears);
2019-08-18 20:06:06 +02:00
// Si c'est ton anniversaire aujourd'hui
2019-09-19 09:43:36 +02:00
if(birthDateDay === parseInt(day) && (parseInt(birthDateMonth) + 1) === parseInt(month))
2019-08-18 20:06:06 +02:00
{
return 'Vous avez ' + ageYears + ' ans. Joyeux Anniversaire! 🥳';
2019-08-16 12:05:56 +02:00
}
else
{
2019-08-18 20:06:06 +02:00
return 'Vous avez ' + ageYears + ' ans, ' + ageMonths + ' mois et ' + ageDays + ' jour(s).';
2019-08-16 12:05:56 +02:00
}
}
else
{
return messageError;
2019-10-13 20:58:13 +02:00
}
2019-08-16 12:05:56 +02:00
}
2019-09-14 17:38:30 +02:00
// Convertis des °C en °F et l'inverse aussi
2019-08-16 12:05:56 +02:00
function convertTemperature(degree, unit) {
if (!isNaN(degree) && unit === "°C")
{
const temperatureValue = ((degree * 9/5) + 32) + " °F";
return temperatureValue;
}
else if (!isNaN(degree) && unit === "°F")
{
const temperatureValue = (degree - 32) * 5/9 + " °C";
return temperatureValue;
}
else
{
return messageError;
}
}
2019-09-14 17:38:30 +02:00
// Convertis la longueur (distance) avec les unités allant de picomètre au Téramètre
2019-08-16 12:05:56 +02:00
function convertDistance (firstValue, unitFirstValue, unitFinalValue) {
2019-10-18 09:55:35 +02:00
const reference = ["pm",null,null,"nm",null,null,"µm",null,null,"mm","cm","dm","m","dam","hm","km",null,null,"Mm",null,null,"Gm",null,null,"Tm"];
const index1 = reference.indexOf(unitFirstValue);
const index2 = reference.indexOf(unitFinalValue);
2019-08-16 12:05:56 +02:00
// Condition qui vérifie si les valeurs entrées sont justes
if (!isNaN(firstValue) && typeof unitFirstValue === 'string' && typeof unitFinalValue === 'string' && (index1.toString() && index2.toString()) != '-1')
{
// Conversion des longueurs :
2019-10-18 09:55:35 +02:00
const difference = index1 - index2;
const result = firstValue*Math.pow(10,difference);
const response = 'Conversion de longueur : ' + formatNumberResult(firstValue).toString() + ' ' + unitFirstValue + ' = ' + formatNumberResult(result) + ' ' + unitFinalValue;
2019-08-16 12:05:56 +02:00
return response;
}
else
{
return messageError;
}
}
2019-08-29 14:53:15 +02:00
// Affiche uniquement les prénoms (qui sont dans la liste) qui commence par la lettre souhaitée
function filterStudents(filteredLetter, students)
{
let filteredStudents = [];
for(let i = 0; i < students.length; i++)
{
2019-08-30 00:00:29 +02:00
let studentBoucle = capitalize(students[i]);
2019-08-29 14:53:15 +02:00
if (studentBoucle[0] === filteredLetter) {
filteredStudents.push(studentBoucle);
}
}
if (filteredStudents.length === 1)
{
return ("Prénom qui commence par " + filteredLetter + " : " + filteredStudents + '.');
}
else if (filteredStudents.length >= 2)
{
// Affiche la liste des prénoms...
2019-10-18 09:55:35 +02:00
const last = filteredStudents[filteredStudents.length - 1]; // Accéde au dernier élément du tableau
const totalfilteredLetterStudents = filteredStudents.length;
2019-08-29 14:53:15 +02:00
filteredStudents.pop(); // Supprime le dernier élément du tableau
// filteredStudents.join(', ') permet de rajouter un espace entre chaque élément du tableau
return ("Prénoms qui commence par " + filteredLetter + " (" + totalfilteredLetterStudents + ") : " + filteredStudents.join(', ') + ' et ' + last + '.');
}
else
{
return ("Il n'y a pas de prénom commencant par " + filteredLetter + ".");
}
}
2019-09-13 21:56:36 +02:00
// Génère aléatoirement une citation ou un proverbe
2019-09-13 14:39:29 +02:00
function getRandomQuote() {
2019-10-18 09:55:35 +02:00
const randomNbr = randomNumber(0, (quotes.length - 1));
const randomQuotes = quotes[randomNbr];
2019-09-13 14:39:29 +02:00
return '" ' + randomQuotes["quote"] + ' " <br> <br> - ' + randomQuotes["source"];
}
2019-09-16 20:39:30 +02:00
// Convertis une valeur dans une devise dans une autre devise
function convertCurrency(value, currency, url) {
2019-10-04 20:10:38 +02:00
function currencyTest(currencyToTest) {
for (let index in correspondancesMonnaie) {
if(currencyToTest === correspondancesMonnaie[index]['currency']) {
return correspondancesMonnaie[index]['symbol'];
}
continue;
}
}
2019-09-13 21:56:36 +02:00
$.ajax({
2019-09-16 20:39:30 +02:00
url : url,
2019-09-13 23:00:41 +02:00
dataType : "json",
2019-09-13 21:56:36 +02:00
success: function (jsonFixer) {
2019-10-04 20:10:38 +02:00
try {
let currencySymboleAPI = eval(`jsonFixer.rates.${currencyTest(currency)}`);
if (currencySymboleAPI === undefined) {
currencySymboleAPI = 1;
}
2019-10-18 09:55:35 +02:00
const exchangeRateYear = jsonFixer.date[0] + jsonFixer.date[1] + jsonFixer.date[2] + jsonFixer.date[3];
const exchangeRateMonth = jsonFixer.date[5] + jsonFixer.date[6];
const exchangeRateDay = jsonFixer.date[8] + jsonFixer.date[9];
2019-10-08 11:18:34 +02:00
$('.results').html(formatNumberResult(value) + ' ' + jsonFixer.base + ' = ' + formatNumberResult((currencySymboleAPI * value).toFixed(2)) + ' ' + currency);
$('.rateDate').html(`Dernier rafraîchissement du taux d'échange : ${exchangeRateDay}/${exchangeRateMonth}/${exchangeRateYear}`);
2019-10-04 20:10:38 +02:00
}
catch (error) {
$('.results').html(messageError);
2019-09-13 21:56:36 +02:00
}
}
});
}
2019-08-16 12:05:56 +02:00
// Convertis des nombres de différentes bases et convertis en UTF-8. (source : http://jsfiddle.net/47zwb41o)
// Texte en Binaire (UTF-8)
2019-09-14 17:38:30 +02:00
function utf8ToBin(s) {
try {
s = unescape( encodeURIComponent(s));
var chr, i = 0, l = s.length, out = '';
for( ; i < l; i ++ ){
chr = s.charCodeAt( i ).toString(2);
while(chr.length % 8 != 0 ){ chr = '0' + chr; }
out += chr;
}
return out;
} catch (error) {
return s;
2019-09-14 17:38:30 +02:00
}
}
// Binaire (UTF-8) en Texte
2019-09-14 17:38:30 +02:00
function binToUtf8(s){
try {
var i = 0, l = s.length, chr, out = '';
for( ; i < l; i += 8){
chr = parseInt( s.substr(i, 8 ), 2).toString(16);
out += '%' + ((chr.length % 2 == 0) ? chr : '0' + chr);
}
return decodeURIComponent(out);
} catch (error) {
return s;
}
}
// Texte en Hexadécimal (UTF-8)
function utf8ToHex (s) {
try {
s = unescape( encodeURIComponent( s ) );
var chr, i = 0, l = s.length, out = '';
for( ; i < l; i++ ){
chr = s.charCodeAt( i ).toString( 16 );
out += ( chr.length % 2 == 0 ) ? chr : '0' + chr;
out += " ";
}
return out;
}
catch (error) {
return s;
}
}
// Hexadécimal (UTF-8) en Texte
function hexToUtf8 (s) {
try {
return decodeURIComponent( s.replace( /../g, '%$&' ) );
}
catch (error) {
return s;
}
}
// Convertis des nombres de différents bases
function convertDecimalBinaryHexadecimal(value, option) {
2019-10-05 17:29:27 +02:00
try {
switch (option) {
case 'DecimalToBinary':
value = value.replace(" ", "");
value = parseInt(value);
if (isNaN(value)) {
return messageError;
} else {
return value.toString(2);
}
case 'BinaryToDecimal':
return formatNumberResult(parseInt(value, 2));
case 'DecimalToHexadecimal':
value = value.replace(" ", "");
value = parseInt(value);
if (isNaN(value)) {
return messageError;
} else {
return value.toString(16).toUpperCase();
}
case 'HexadecimalToDecimal':
return formatNumberResult(parseInt(value, 16));
case 'BinaryToHexadecimal':
value = parseInt(value, 2);
if (isNaN(value)) {
return messageError;
} else {
return parseInt(value).toString(16).toUpperCase();
}
case 'HexadecimalToBinary':
value = parseInt(value, 16);
if (isNaN(value)) {
return messageError;
} else {
return parseInt(value).toString(2);
}
default:
2019-10-05 17:29:27 +02:00
return messageError;
}
}
catch (error) {
return messageError;
}
}
// Convertis un nombre arabe en nombre romain
function convertArabicToRoman(nombre) {
// Initialisation de la variable qui va contenir le résultat de la conversion
let chiffresRomains = "";
/*
Étapes pour écrire un nombre romain :
On vérifie quand le nombre arabe est >= à la plus grande valeur possible dans la table de correspondance des nombres romains de haut en bas puis on rajoute la lettre romaine correspondante à la plus grande valeur possible dans la variable chiffresRomains et on soustrait la valeur du chiffre romain qu'on vient d'ajouter au nombre arabe puis on répète l'opération jusqu'à nombre arabe vaut 0...
Exemple avec 27 :
27 - X (10) = 17
17 - X (10) = 7
7 - V (5) = 2
2 - I (1) = 1
1 - I (1) = 0
XXVII
*/
function extraireChiffreRomain(valeurLettre, lettres) {
while (nombre >= valeurLettre) {
chiffresRomains = chiffresRomains + lettres;
nombre = nombre - valeurLettre;
}
}
correspondancesRomainArabe.forEach(correspondance => {
extraireChiffreRomain(correspondance[0], correspondance[1]);
})
if (chiffresRomains === '') {
return messageError;
} else {
return chiffresRomains;
}
2019-09-21 22:40:16 +02:00
}
// Convertis un nombre romain en nombre arabe
function convertRomanToArabic(str) {
let result = 0;
for (let i = 0;i < correspondancesRomainArabe.length; i++) {
while (str.indexOf(correspondancesRomainArabe[i][1]) === 0){
// Adding the decimal value to our result counter
result += correspondancesRomainArabe[i][0];
// Remove the matched Roman letter from the beginning
str = str.replace(correspondancesRomainArabe[i][1],'');
}
}
2019-10-08 13:48:24 +02:00
if (str != '') {
result = 0;
}
return result;
}
2019-09-21 22:40:16 +02:00
// Vérifie si un nombre fait partie des nombres d'Armstrong ou non
function armstrongNumber(number) {
2019-09-22 10:44:13 +02:00
let numberString = number.toString();
let numberStringLength = numberString.length;
2019-09-21 22:40:16 +02:00
let result = 0;
let resultString = "";
2019-09-22 10:44:13 +02:00
for (let i = 0; i < numberStringLength; i++) {
result = result + parseInt(numberString[i])**numberStringLength;
resultString = resultString + " + " + numberString[i] + "<sup>" + numberStringLength + "</sup>";
2019-09-21 22:40:16 +02:00
}
number = formatNumberResult(number);
2019-09-22 10:44:13 +02:00
if (result === number) {
return `${number} est un nombre d'Armstrong, car ${resultString.slice(2)} = ${formatNumberResult(result)}.`;
2019-09-21 22:40:16 +02:00
} else {
return `${number} n'est pas un nombre d'Armstrong, car ${resultString.slice(2)} = ${formatNumberResult(result)}.`;
2019-09-21 22:40:16 +02:00
}
2019-10-11 21:30:05 +02:00
}
// Retourne un tableau contenant toutes les possibilités d'anagramme d'un mot
function stringPermutations(string) {
let results = [];
if (string.length === 1) {
results.push(string);
return results;
}
for (let i = 0; i < string.length; i++) {
let firstChar = string[i];
let charsLeft = string.substring(0, i) + string.substring(i + 1);
let innerPermutations = stringPermutations(charsLeft);
for (let i = 0; i < innerPermutations.length; i++) {
results.push(firstChar + innerPermutations[i]);
}
}
return results;
2019-08-16 12:05:56 +02:00
}