Używamy cookies, żeby zwiększyć Twoje doświadczenia na stronie
CodeWorlds

ES2024 i ES2025 - Najnowsze funkcje JavaScript

Dr. Henry Wu właśnie wrócił z konferencji programistów. "JavaScript ciągle ewoluuje," mówi. "Najnowsze wersje ECMAScript przynoszą funkcje, które znacznie uproszczą nasz kod!"

ES2024 - Najważniejsze nowości

1. Object.groupBy() i Map.groupBy()

Grupowanie elementów tablicy według klucza - bez bibliotek zewnętrznych!

1const dinosaurs = [
2  { name: 'Rex', type: 'carnivore', sector: 7 },
3  { name: 'Blue', type: 'carnivore', sector: 3 },
4  { name: 'Sarah', type: 'herbivore', sector: 5 },
5  { name: 'Bronty', type: 'herbivore', sector: 5 },
6  { name: 'Delta', type: 'carnivore', sector: 3 }
7];
8
9// Grupowanie po typie
10const byType = Object.groupBy(dinosaurs, dino => dino.type);
11console.log(byType);
12// {
13//   carnivore: [{ name: 'Rex', ... }, { name: 'Blue', ... }, { name: 'Delta', ... }],
14//   herbivore: [{ name: 'Sarah', ... }, { name: 'Bronty', ... }]
15// }
16
17// Grupowanie po sektorze
18const bySector = Object.groupBy(dinosaurs, dino => `Sector-${dino.sector}`);
19console.log(bySector);
20
21// Map.groupBy - gdy potrzebujesz Map zamiast obiektu
22const byTypeMap = Map.groupBy(dinosaurs, dino => dino.type);
23console.log(byTypeMap.get('carnivore'));

2. Metody tablicowe bez mutacji

Nowe metody, które zwracają nową tablicę zamiast modyfikować oryginalną:

1const sectors = ['Sector-1', 'Sector-7', 'Sector-3', 'Sector-5'];
2
3// ❌ Stare metody MUTUJĄ oryginalną tablicę
4const oldWay = [...sectors];
5oldWay.sort(); // Zmienia oldWay!
6
7// ✅ toSorted() - sortuje bez mutacji
8const sorted = sectors.toSorted();
9console.log(sorted);   // ['Sector-1', 'Sector-3', 'Sector-5', 'Sector-7']
10console.log(sectors);  // ['Sector-1', 'Sector-7', 'Sector-3', 'Sector-5'] - niezmienione!
11
12// ✅ toReversed() - odwraca bez mutacji
13const reversed = sectors.toReversed();
14console.log(reversed); // ['Sector-5', 'Sector-3', 'Sector-7', 'Sector-1']
15console.log(sectors);  // Nadal oryginalne!
16
17// ✅ toSpliced() - splice bez mutacji
18const withNew = sectors.toSpliced(1, 1, 'Sector-9', 'Sector-10');
19console.log(withNew);  // ['Sector-1', 'Sector-9', 'Sector-10', 'Sector-3', 'Sector-5']
20
21// ✅ with() - zamień element bez mutacji
22const updated = sectors.with(1, 'Sector-ALPHA');
23console.log(updated);  // ['Sector-1', 'Sector-ALPHA', 'Sector-3', 'Sector-5']
24
25// Praktyczny przykład: sortowanie dinozaurów
26const dinoList = [
27  { name: 'Rex', dangerLevel: 10 },
28  { name: 'Blue', dangerLevel: 8 },
29  { name: 'Sarah', dangerLevel: 3 }
30];
31
32// Sortuj po poziomie zagrożenia (malejąco) bez mutacji
33const byDanger = dinoList.toSorted((a, b) => b.dangerLevel - a.dangerLevel);
34console.log(byDanger[0].name); // 'Rex'

3. Promise.withResolvers()

Łatwiejsze tworzenie Promise z zewnętrznym resolve/reject:

1// ❌ Stary sposób - niewygodny
2let externalResolve, externalReject;
3const oldPromise = new Promise((resolve, reject) => {
4  externalResolve = resolve;
5  externalReject = reject;
6});
7
8// ✅ Nowy sposób z Promise.withResolvers()
9const { promise, resolve, reject } = Promise.withResolvers();
10
11// Teraz możemy resolve/reject z dowolnego miejsca
12setTimeout(() => {
13  resolve('Operacja zakończona!');
14}, 1000);
15
16promise.then(console.log); // "Operacja zakończona!" po 1 sekundzie

ES2025 - Najnowsze funkcje

1. Nowe metody Set

Operacje na zbiorach - wreszcie wbudowane w JavaScript!

1const carnivores = new Set(['Rex', 'Blue', 'Delta', 'Echo']);
2const sectorA = new Set(['Rex', 'Sarah', 'Delta']);
3
4// intersection() - elementy wspólne
5const dangerousInA = carnivores.intersection(sectorA);
6console.log([...dangerousInA]); // ['Rex', 'Delta']
7
8// difference() - elementy tylko w pierwszym zbiorze
9const safeInA = sectorA.difference(carnivores);
10console.log([...safeInA]); // ['Sarah']
11
12// union() - wszystkie elementy z obu zbiorów
13const allKnown = carnivores.union(sectorA);
14console.log([...allKnown]); // ['Rex', 'Blue', 'Delta', 'Echo', 'Sarah']
15
16// symmetricDifference() - elementy tylko w jednym ze zbiorów
17const exclusive = carnivores.symmetricDifference(sectorA);
18console.log([...exclusive]); // ['Blue', 'Echo', 'Sarah']
19
20// isSubsetOf() - czy jest podzbiorem
21const smallGroup = new Set(['Rex', 'Blue']);
22console.log(smallGroup.isSubsetOf(carnivores)); // true
23
24// isSupersetOf() - czy zawiera wszystkie elementy
25console.log(carnivores.isSupersetOf(smallGroup)); // true
26
27// isDisjointFrom() - czy nie mają wspólnych elementów
28const herbivores = new Set(['Sarah', 'Bronty', 'Tricy']);
29console.log(carnivores.isDisjointFrom(herbivores)); // true

2. Promise.try()

Bezpieczne wykonanie funkcji w kontekście Promise:

1function riskyOperation(shouldThrow) {
2  if (shouldThrow) {
3    throw new Error('Synchroniczny błąd!');
4  }
5  return 'Sukces';
6}
7
8// ✅ Nowy sposób z Promise.try()
9const result = Promise.try(() => riskyOperation(false));
10result.then(console.log); // 'Sukces'
11
12const error = Promise.try(() => riskyOperation(true));
13error.catch(err => console.error(err.message)); // 'Synchroniczny błąd!'

3. Import Attributes (JSON Modules)

Importowanie JSON bezpośrednio:

1// Importowanie pliku JSON z atrybutem typu
2import dinoConfig from './dinosaurs.json' with { type: 'json' };
3
4console.log(dinoConfig.species);
5
6// Dynamiczny import z atrybutami
7const config = await import('./config.json', { with: { type: 'json' } });

Sprawdzanie wsparcia przeglądarki

1const es2024Support = {
2  objectGroupBy: typeof Object.groupBy === 'function',
3  arrayToSorted: typeof [].toSorted === 'function',
4  arrayToReversed: typeof [].toReversed === 'function',
5  arrayWith: typeof [].with === 'function',
6  promiseWithResolvers: typeof Promise.withResolvers === 'function'
7};
8
9const es2025Support = {
10  setIntersection: typeof Set.prototype.intersection === 'function',
11  setDifference: typeof Set.prototype.difference === 'function',
12  promiseTry: typeof Promise.try === 'function'
13};
14
15console.log('ES2024 Support:', es2024Support);
16console.log('ES2025 Support:', es2025Support);

Podsumowanie

ES2024 i ES2025 przynoszą:

  1. Object.groupBy() - grupowanie danych bez lodash
  2. toSorted(), toReversed(), with() - immutability bez spread operator
  3. Promise.withResolvers() - łatwiejsze zarządzanie Promise
  4. Metody Set - operacje na zbiorach wbudowane w język

Pamiętajcie sprawdzać kompatybilność przeglądarek i używać polyfilli gdy potrzeba!

Przejdź do CodeWorlds