16

Utilitaires JavaScript

Math, Date, JSON, Intl, Console

JavaScript fournit des objets globaux puissants pour les opérations mathématiques, la manipulation de dates, le parsing JSON, l'internationalisation et le debugging.

🔢 Math - Opérations Mathématiques

// CONSTANTES
Math.PI;      // 3.141592653589793
Math.E;       // 2.718281828459045 (nombre d'Euler)

// ARRONDIS
Math.round(4.7);    // 5 (arrondi standard)
Math.ceil(4.1);     // 5 (arrondi supérieur)
Math.floor(4.9);    // 4 (arrondi inférieur)
Math.trunc(4.9);    // 4 (supprime la partie décimale)

// MIN / MAX
Math.min(5, 2, 8, 1);     // 1
Math.max(5, 2, 8, 1);     // 8
Math.max(...[5, 2, 8]);   // 8 (avec spread)

// PUISSANCE & RACINE
Math.pow(2, 3);     // 8 (2³)
2 ** 3;             // 8 (opérateur moderne)
Math.sqrt(16);      // 4 (racine carrée)
Math.cbrt(27);      // 3 (racine cubique)

// ALÉATOIRE
Math.random();              // 0 ≤ x < 1
Math.floor(Math.random() * 10);  // 0-9
Math.floor(Math.random() * (max - min + 1)) + min;  // Entre min et max

// TRIGONOMÉTRIE (radians)
Math.sin(Math.PI / 2);  // 1
Math.cos(0);            // 1
Math.tan(Math.PI / 4);  // 1

// AUTRES
Math.abs(-5);       // 5 (valeur absolue)
Math.sign(-5);      // -1 (signe: -1, 0, 1)
Math.log(Math.E);   // 1 (logarithme naturel)
🎲 Random entre min-max
function randomInt(min, max) {
    return Math.floor(
        Math.random() * (max - min + 1)
    ) + min;
}
📐 Arrondir à N décimales
function round(num, decimals) {
    const factor = 10 ** decimals;
    return Math.round(num * factor) 
        / factor;
}
📊 Clamp (limiter)
function clamp(num, min, max) {
    return Math.min(
        Math.max(num, min), 
        max
    );
}

📅 Date - Manipulation de Dates

// CRÉATION
const now = new Date();                    // Maintenant
const specific = new Date('2024-12-25');   // Date spécifique
const timestamp = new Date(1609459200000); // Depuis timestamp

// GETTERS
now.getFullYear();   // 2024
now.getMonth();      // 0-11 (⚠️ Janvier = 0)
now.getDate();       // 1-31 (jour du mois)
now.getDay();        // 0-6 (dimanche = 0)
now.getHours();      // 0-23
now.getMinutes();    // 0-59
now.getSeconds();    // 0-59
now.getTime();       // Timestamp en ms

// SETTERS
now.setFullYear(2025);
now.setMonth(11);    // Décembre
now.setDate(25);

// FORMATAGE (Intl recommandé, voir plus bas)
now.toLocaleDateString('fr-FR');  // "25/12/2024"
now.toLocaleTimeString('fr-FR');  // "14:30:00"
now.toISOString();                // "2024-12-25T14:30:00.000Z"

// CALCULS
const tomorrow = new Date(now);
tomorrow.setDate(tomorrow.getDate() + 1);

const diff = date2 - date1;  // Différence en ms
const daysDiff = diff / (1000 * 60 * 60 * 24);
Méthode Description Exemple
Date.now() Timestamp actuel (ms) 1609459200000
date.getTime() Timestamp de la date 1609459200000
date.toISOString() Format ISO 8601 "2024-12-25T14:30:00.000Z"
date.toLocaleDateString() Format local "25/12/2024"

📦 JSON - Sérialisation

// STRINGIFY (Objet → String)
const obj = { name: 'Alice', age: 25, active: true };
const json = JSON.stringify(obj);
// '{"name":"Alice","age":25,"active":true}'

// Avec indentation (pretty print)
JSON.stringify(obj, null, 2);
/*
{
  "name": "Alice",
  "age": 25,
  "active": true
}
*/

// Avec filtre de propriétés
JSON.stringify(obj, ['name', 'age']);  // Seulement name et age

// PARSE (String → Objet)
const parsed = JSON.parse(json);
// { name: 'Alice', age: 25, active: true }

// ⚠️ ERREURS COURANTES
JSON.parse('undefined');     // ❌ SyntaxError
JSON.parse("{'key': 'val'}"); // ❌ Guillemets simples invalides
JSON.parse('{"key": "val"}'); // ✅ Guillemets doubles

// TYPES SUPPORTÉS
JSON.stringify({
    string: 'text',
    number: 42,
    boolean: true,
    null: null,
    array: [1, 2, 3],
    object: { nested: true }
});

// TYPES NON SUPPORTÉS (deviennent null ou sont ignorés)
JSON.stringify({
    func: () => {},      // Ignoré
    undef: undefined,    // Ignoré
    date: new Date(),    // Converti en string ISO
    symbol: Symbol('s')  // Ignoré
});

🌍 Intl - Internationalisation

// NOMBRES
const num = 1234567.89;

new Intl.NumberFormat('fr-FR').format(num);
// "1 234 567,89"

new Intl.NumberFormat('en-US').format(num);
// "1,234,567.89"

// Devises
new Intl.NumberFormat('fr-FR', {
    style: 'currency',
    currency: 'EUR'
}).format(99.99);
// "99,99 €"

// Pourcentages
new Intl.NumberFormat('fr-FR', {
    style: 'percent'
}).format(0.75);
// "75 %"

// DATES
const date = new Date('2024-12-25T14:30:00');

new Intl.DateTimeFormat('fr-FR').format(date);
// "25/12/2024"

new Intl.DateTimeFormat('fr-FR', {
    dateStyle: 'full',
    timeStyle: 'short'
}).format(date);
// "mercredi 25 décembre 2024 à 14:30"

// DATES RELATIVES
const rtf = new Intl.RelativeTimeFormat('fr', { numeric: 'auto' });
rtf.format(-1, 'day');   // "hier"
rtf.format(2, 'week');   // "dans 2 semaines"
rtf.format(-3, 'month'); // "il y a 3 mois"

// LISTES
const list = new Intl.ListFormat('fr', { style: 'long', type: 'conjunction' });
list.format(['Alice', 'Bob', 'Charlie']);
// "Alice, Bob et Charlie"

🎮 Playground Utilitaires

Testez les différentes APIs.

Cliquez sur un bouton pour voir la démo

🖥️ Console - Debugging

// LOGS DE BASE
console.log('Message simple');
console.info('Information');
console.warn('Avertissement');  // ⚠️ Jaune
console.error('Erreur');         // ❌ Rouge

// FORMATAGE
console.log('User: %s, Age: %d', 'Alice', 25);
console.log('%cStyled!', 'color: blue; font-size: 20px');

// OBJETS
const user = { name: 'Alice', age: 25 };
console.log(user);        // Objet cliquable
console.dir(user);        // Vue détaillée
console.table([user]);    // Tableau formaté

// GROUPES
console.group('Détails');
console.log('Item 1');
console.log('Item 2');
console.groupEnd();

// TEMPS
console.time('operation');
// ... code ...
console.timeEnd('operation');  // "operation: 123ms"

// COMPTEUR
console.count('clicks');  // clicks: 1
console.count('clicks');  // clicks: 2
console.countReset('clicks');

// ASSERTIONS
console.assert(1 === 2, 'Les valeurs ne sont pas égales');
// Affiche l'erreur si false

// TRACE
function a() { b(); }
function b() { console.trace('Stack trace'); }
a();  // Affiche la pile d'appels
Best Practice : Utilisez Intl pour le formatage (dates, nombres, devises) au lieu de méthodes manuelles. Préférez Date.now() à new Date().getTime() pour les timestamps. Validez toujours le JSON avant JSON.parse() avec try/catch.
⚠️ Pièges : Les mois en JavaScript sont 0-indexed (Janvier = 0). JSON.stringify() ignore les fonctions et undefined. Math.random() n'est pas cryptographiquement sûr (utilisez crypto.getRandomValues() pour la sécurité).
← Classes Suivant: Strings →