Panduan konsep Functional Programming dalam JavaScript dengan contoh praktis
Functional Programming (FP) adalah paradigma pemrograman di mana komputasi diperlakukan sebagai evaluasi fungsi matematika dan menghindari perubahan state dan data yang mutable.
// Pure Function
function add(a, b) {
return a + b;
}
// Higher-Order Function
function multiplyBy(factor) {
return function(num) {
return num * factor;
};
}
// Immutable Data
const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4]; // Not modifying original
đ Penjelasan Detail:
âĸ Pure Function
- Fungsi yang selalu menghasilkan output sama untuk input sama
âĸ Higher-Order Function
- Fungsi yang menerima/mengembalikan fungsi lain
âĸ Immutable Data
- Data yang tidak bisa diubah setelah dibuat
âĸ First-Class Functions
- Fungsi diperlakukan seperti variabel biasa
âĸ Function Composition
- Menggabungkan fungsi untuk operasi kompleks
// Currying
const curryAdd = a => b => a + b;
const addFive = curryAdd(5);
addFive(3); // 8
// Function Composition
const compose = (f, g) => x => f(g(x));
const toUpperCase = str => str.toUpperCase();
const exclaim = str => `${str}!`;
const shout = compose(exclaim, toUpperCase);
// Recursion
function factorial(n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
Kode lebih mudah diprediksi, di-test, dan di-debug karena tidak ada side effects. Juga memudahkan parallel processing dan code reuse.
// Array Methods (FP Style)
const numbers = [1, 2, 3, 4, 5];
// Map (Transform)
numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
// Filter (Select)
numbers.filter(n => n % 2 === 0); // [2, 4]
// Reduce (Accumulate)
numbers.reduce((acc, n) => acc + n, 0); // 15
// Chaining
numbers
.filter(n => n > 2)
.map(n => n * 3)
.reduce((acc, n) => acc + n, 0); // 36
đ Penjelasan Detail:
âĸ Map - Membuat array baru dengan transformasi tiap elemen
âĸ Filter - Membuat array baru hanya dengan elemen yang memenuhi kondisi
âĸ Reduce - Menggabungkan semua elemen menjadi single value
âĸ Method Chaining memungkinkan operasi berurutan tanpa variabel intermediate
âĸ Semua method ini tidak mengubah array asli (immutable)
// Functors
const Box = x => ({
map: f => Box(f(x)),
fold: f => f(x),
inspect: () => `Box(${x})`
});
// Monads
const Right = x => ({
map: f => Right(f(x)),
fold: (f, g) => g(x)
});
// Lenses
const lens = (getter, setter) => ({
get: obj => getter(obj),
set: (val, obj) => setter(val, obj)
});
Functors adalah container yang bisa di-mapping. Monads menangani efek samping dan komposisi. Lenses memungkinkan immutability dengan update bersarang.
Mulai dengan fungsi kecil dan pure, hindari mutasi data, gunakan higher-order functions, dan komposisi daripada inheritance.
// â
Good - Pure, small, composable
const calculateTotal = items =>
items
.map(item => item.price * item.quantity)
.reduce((acc, price) => acc + price, 0);
// â Avoid - Impure, mutable
let total = 0;
for (let i = 0; i < items.length; i++) {
total += items[i].price * items[i].quantity;
}
// â
Better - Point-free style
const doubleAll = map(n => n * 2);
const sumAll = reduce((acc, n) => acc + n, 0);
const processNumbers = compose(sumAll, doubleAll);
đ Penjelasan Detail:
âĸ Gunakan pure functions - Lebih mudah diprediksi dan di-test
âĸ Hindari side effects - Minimalkan interaksi dengan dunia luar dalam fungsi
âĸ Immutability - Gunakan spread operator, map, filter daripada push/splice
âĸ Function composition - Gabungkan fungsi kecil menjadi operasi kompleks
âĸ Declarative over imperative - Fokus pada "what" bukan "how"
Beberapa library populer untuk FP di JavaScript: Ramda, Lodash/fp, Immutable.js, Sanctuary, Folktale.
đ Sumber Belajar Lanjutan:
âĸ Mostly Adequate Guide - Buku FP gratis oleh Professor Frisby
âĸ Functional Light JavaScript - Kyle Simpson
âĸ Ramda Documentation - Dokumentasi library FP Ramda
âĸ Fantasy Land Spec - Spesifikasi algebraic JavaScript
âĸ Functional Programming Jargon - Glosarium istilah FP