🎓 Funkcje wyższego rzędu
Funkcje wyższego rzędu przyjmują inne funkcje jako argumenty lub je zwracają.
map
let numbers = [1, 2, 3];
let doubled = numbers.map(x => x * 2);
filter
let evens = [1,2,3,4,5].filter(x => x % 2 == 0);
reduce
let sum = [1,2,3,4,5].reduce((acc, x) => acc + x, 0);
find / findIndex
let first = [1,2,3,4].find(x => x > 2);
let idx = [1,2,3,4].findIndex(x => x > 2);
every / some
let allPos = [1,2,3].every(x => x > 0);
let hasNeg = [1,-2,3].some(x => x < 0);
Tworzenie własnych HOF
fn twice(f) {
return fn(x) {
return f(f(x));
};
}
let double = x => x * 2;
let quadruple = twice(double);
print(quadruple(5));