[JS] Functional Programming

จดๆ Note ไว้ เกี่ยวกับ Functional Programming โดยใช้ JavaScript เป็นต้วอย่าง function เป็น Input หรือเป็น Parameter ได้ จาก Code ด้านล่างจะเป็นตัวอย่างที่แสดง

  • Pure function - no side effects / รันทุกรอบได้ผลลัพธ์เหมือนกัน
  • Higher-order function รับ function เข้าไปเป็น Parameter ถ้าใน Code เอา map + double ทำเป็น function composition เอา function หลายๆอันมาทำงานร่วมกัน
  • รวมถึงการทำ Chaining functional
// Pure function: does not modify external state, returns the same output for same input
const add = (a, b) => a + b;

// Higher-order function: takes a function as an argument
const map = (fn, arr) => arr.map(fn);

// Example usage: doubling each number in an array
const double = x => x * 2;
const numbers = [1, 2, 3, 4];
const doubledNumbers = map(double, numbers); // [2, 4, 6, 8]

// Chaining functional methods
const result = numbers
  .filter(n => n % 2 === 0)

ยกตัวอย่างอีกเคสนึง อย่างตัว EmailValidator

// Pure function: checks if the string contains '@'
const hasAtSymbol = email => email.includes('@');

// Pure function: checks for a valid domain (after "@", must have a ".")
const hasValidDomain = email => {
  const parts = email.split('@');
  return parts.length === 2 && parts[1].includes('.');
};

// Pure function: checks if the email does not have spaces
const hasNoSpaces = email => !/\s/.test(email);

// Pure function: checks if the email matches a simple regex pattern
const matchesPattern = email =>
  /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

// Higher-order function: combines multiple validators
const validateEmail = email => [
  hasAtSymbol,
  hasValidDomain,
  hasNoSpaces,
  matchesPattern
].every(validator => validator(email));

// Example usage
const emails = [
  "[email protected]",
  "invalid [email protected]",
  "noatsymbol.com",
  "missingdomain@com"
];

const results = emails.map(email => ({
  email,
  isValid: validateEmail(email)
}));

console.log(results);
/*
[
  { email: '[email protected]', isValid: true },
  { email: 'invalid [email protected]', isValid: false },
  { email: 'noatsymbol.com', isValid: false },
  { email: 'missingdomain@com', isValid: false }
]
*/

เมื่อมี function หลายๆอัน เรายุบรวมมันว่าเป็น Service เช่น EmailValidator เกิดจากการเอา Function หลายๆตัวอย่าง hasAtSymbol / hasValidDomain / hasNoSpaces / matchesPattern มาทำงานร่วมกัน

สรุป Key Functional Programming Principles

  • Each function is pure - no side effects / รันทุกรอบได้ผลลัพธ์เหมือนกัน
  • Smaller functions รวมกัน composed เพื่อมารอบรับ Business ที่ซับซ้อนขึ้น
    - Pure function รวมแต่ละหน้าที่คล้ายกลาย Service อะไรที่เหมือนกัน
    - Service หลายตัวทำงานร่วมกัน มันก็ คือ ตัว Use Case
    - Use Case หลายตัวรวมกันได้เป็น Application
  • All data is immutable - no mutation of input arrays/objects


Discover more from naiwaen@DebuggingSoft

Subscribe to get the latest posts sent to your email.