Functional Programming
Functional programming (FP) is a paradigm that treats computation as evaluation of mathematical functions. It emphasizes pure functions, immutability, and function composition producing code that is easier to test, reason about, and parallelize.
Contents 4 Sections
1Core Concepts
Pure Functions same input always produces same output, no side effects ```javascript // Impure: depends on external state, has side effects let total = 0; function addToTotal(n) { total += n; return total; }
// Pure: no external dependency, no mutation function add(a, b) { return a + b; }
// Impure: logs (side effect), reads Date (non-deterministic) function createUser(name) { console.log("Creating user"); return { name, createdAt: new Date() }; }
// Pure: deterministic, no side effects function createUser(name, timestamp) { return { name, createdAt: timestamp }; } ```
Immutability never modify data, create new values ```javascript // Mutable (avoid) const user = { name: "Alice", score: 5 }; user.score++;
// Immutable (FP style) const updated = { ...user, score: user.score + 1 };
// Array operations (non-mutating) const doubled = nums.map(n => n * 2); // new array const filtered = nums.filter(n => n > 0); // new array const sorted = [...nums].sort(); // copy then sort ```
Referential Transparency expression can be replaced with its value without changing program behavior. Enables memoization.
2Higher-Order Functions
Functions as First-Class Values pass them, return them, store them.
// Map: transform each element
const prices = [10, 25, 8, 50];
const withTax = prices.map(p => p * 1.1); // [11, 27.5, 8.8, 55]// Filter: keep elements matching predicate const affordable = prices.filter(p => p < 20); // [10, 8]
// Reduce: fold list into single value const total = prices.reduce((acc, p) => acc + p, 0); // 93
// FlatMap: map + flatten one level const sentences = ["hello world", "foo bar"]; const words = sentences.flatMap(s => s.split(" ")); // ["hello","world","foo","bar"]
// Compose: combine functions right-to-left const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x); const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const processOrder = pipe( validateOrder, applyDiscount, calculateShipping, formatForDB ); ```
Currying transform multi-arg function into chain of single-arg functions ```javascript const multiply = a => b => a * b; const double = multiply(2); // partially applied const triple = multiply(3); double(5); // 10 triple(5); // 15
// Real use: reusable validators const isGreaterThan = min => x => x > min; const isPositive = isGreaterThan(0); const isAdult = isGreaterThan(17); ```
3Algebraic Data Types
Maybe / Option represent nullable values safely ```typescript // Instead of: null checks everywhere const user = getUser(id); if (user && user.address && user.address.city) { ... }
// Option/Maybe monad
type Option
const user = getUser(id); // Option
Either / Result represent success or failure without exceptions
```typescript
type Result
function parseAge(str: string): Result
const result = parseAge("30"); if (result.ok) console.log(result.value); else console.error(result.error); ```
TypeScript Discriminated Unions (equivalent of ADTs) ```typescript type Shape = | { kind: "circle"; radius: number } | { kind: "rect"; w: number; h: number };
function area(s: Shape): number { switch (s.kind) { case "circle": return Math.PI * s.radius ** 2; case "rect": return s.w * s.h; } } ```
4FP in Practice
Functional React React naturally fits FP: pure render functions, immutable state. ```jsx // Pure component: same props → same output const UserCard = ({ name, email }) => (
{name}
{email}
// Derived state via pure functions (no mutations) const expensiveItems = items.filter(i => i.price > 100); const totalRevenue = orders.reduce((sum, o) => sum + o.total, 0); const activeUserNames = users.filter(u => u.active).map(u => u.name); ```
Functional Lodash / Ramda ```javascript import * as R from "ramda";
const processUsers = R.pipe( R.filter(R.propEq("active", true)), R.map(R.pick(["id", "name", "email"])), R.sortBy(R.prop("name")) ); ```
Testing Pure Functions trivial because no side effects
``javascript
test("calculateDiscount", () => {
expect(calculateDiscount(100, 0.1)).toBe(90);
expect(calculateDiscount(100, 0.5)).toBe(50);
expect(calculateDiscount(0, 0.1)).toBe(0);
});
// No mocks, no setup just call and assert
``
- When to Use FP
- Data transformation pipelines (ETL, analytics)
- Event handlers and React components
- Validation and parsing logic
- Configuration and DSLs
- Concurrent/parallel processing (immutability prevents races)
Explore the Full Portfolio
This is the complete portfolio of Sufi Khan Sulaiman, a technology leader specialising in B2B commerce and digital automation. Start from the Home page for the overview, then move through two decades of career experience across FLIR Systems, Lorex Technology, and 1c Platform, and the full catalogue of project case studies spanning headless commerce migrations, AI recommendation engines, and multi-channel fulfilment systems.
The skills and certifications page maps the technical and leadership capabilities behind the work, while the articles and the knowledge base break down the thinking into actionable frameworks. For hands-on learning, the tutorials and applications sections cover practical builds from front-end fundamentals to full-stack web apps.
For consulting engagement, the expertise page outlines service offerings, the ecommerce hub covers platform architecture and automation strategy, and the ecommerce guide (PDF) is a downloadable 55-page field manual. When you are ready to talk, the contact page is the direct line.