📛 Functional Programming

Panduan konsep Functional Programming dalam JavaScript dengan contoh praktis

📌 Elements

💡 Dasar Functional Programming

Functional Programming (FP) adalah paradigma pemrograman di mana komputasi diperlakukan sebagai evaluasi fungsi matematika dan menghindari perubahan state dan data yang mutable.

fp-basics.js
// 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

đŸ› ī¸ Features

fp-features.js
// 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);
}

â„šī¸ Keuntungan FP

Kode lebih mudah diprediksi, di-test, dan di-debug karena tidak ada side effects. Juga memudahkan parallel processing dan code reuse.

📊 Basic Tables

fp-concepts.js
// 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)

🚀 Advanced Table

advanced-fp.js
// 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)
});

â„šī¸ Advanced FP Concepts

Functors adalah container yang bisa di-mapping. Monads menangani efek samping dan komposisi. Lenses memungkinkan immutability dengan update bersarang.

💡 Pro Tips

đŸŽ¯ Best Practices FP

Mulai dengan fungsi kecil dan pure, hindari mutasi data, gunakan higher-order functions, dan komposisi daripada inheritance.

fp-tips.js
// ✅ 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"

🌐 Info

📚 Library FP JavaScript

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