➡️ Arrow Functions
Arrow functions to skrócona składnia dla funkcji anonimowych.
Składnia
let double = x => x * 2;
let add = (a, b) => a + b;
let greet = () => "Hello!";
let complex = (x) => {
let result = x * 2;
return result + 1;
};
Użycie z metodami kolekcji
let numbers = [1, 2, 3, 4, 5];
let squared = numbers.map(x => x * x);
let evens = numbers.filter(x => x % 2 == 0);
let sum = numbers.reduce((acc, x) => acc + x, 0);
let found = numbers.find(x => x > 3);
let allPositive = numbers.every(x => x > 0);
let hasEven = numbers.some(x => x % 2 == 0);
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);
Function Composition (>>)
let double = x => x * 2;
let addOne = x => x + 1;
let square = x => x * x;
let doubleThenAdd = double >> addOne;
print(doubleThenAdd(5));
let pipeline = addOne >> double >> square;
print(pipeline(3));
Pipe operator (|>)
fn double(x) { return x * 2; }
fn addTen(x) { return x + 10; }
let result = 5 |> double |> addTen;
print(result);
💡 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.