➡️ Arrow Functions

Arrow functions to skrócona składnia dla funkcji anonimowych.

Składnia

// Jeden parametr - nawiasy opcjonalne let double = x => x * 2; // Wiele parametrów - nawiasy wymagane let add = (a, b) => a + b; // Bez parametrów let greet = () => "Hello!"; // Z blokiem (dla wielu instrukcji) let complex = (x) => { let result = x * 2; return result + 1; };

Użycie z metodami kolekcji

let numbers = [1, 2, 3, 4, 5]; // Map let squared = numbers.map(x => x * x); // [1, 4, 9, 16, 25] // Filter let evens = numbers.filter(x => x % 2 == 0); // [2, 4] // Reduce let sum = numbers.reduce((acc, x) => acc + x, 0); // 15 // Find let found = numbers.find(x => x > 3); // 4 // Every / Some let allPositive = numbers.every(x => x > 0); // true let hasEven = numbers.some(x => x % 2 == 0); // true

Chainowanie

let result = [1, 2, 3, 4, 5, 6] .filter(x => x % 2 == 0) .map(x => x * 10) .reduce((a, b) => a + b, 0); print(result); // 120

Function Composition (>>)

let double = x => x * 2; let addOne = x => x + 1; let square = x => x * x; // Kompozycja: najpierw double, potem addOne let doubleThenAdd = double >> addOne; print(doubleThenAdd(5)); // 11 // Łańcuch kompozycji let pipeline = addOne >> double >> square; print(pipeline(3)); // 64

Pipe operator (|>)

fn double(x) { return x * 2; } fn addTen(x) { return x + 10; } // Zamiast: addTen(double(5)) let result = 5 |> double |> addTen; print(result); // 20
💡 Kiedy używać arrow functions?

Arrow functions są idealne dla krótkich, jednolinijkowych funkcji - szczególnie jako argumenty dla map, filter, reduce. Dla dłuższych funkcji z wieloma instrukcjami używaj normalnej składni fn.