Lab 08: Functional Programming

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Overview

Apply functional programming in JavaScript: pure functions, immutability, map/filter/reduce, currying, function composition with compose/pipe, point-free style, and an introduction to transducers.


Step 1: Pure Functions & Side Effects

// IMPURE — depends on external state, mutates input
let total = 0;
function addToTotal(amount) {
  total += amount; // Side effect: modifies external state
  return total;
}

// PURE — same input always gives same output, no side effects
function add(a, b) { return a + b; }
function multiply(a, b) { return a * b; }

// Impure: mutates the array
function pushItem(arr, item) {
  arr.push(item); // Mutation!
  return arr;
}

// Pure: returns new array
function appendItem(arr, item) {
  return [...arr, item];
}

// Benefits of pure functions:
const arr = [1, 2, 3];
const newArr = appendItem(arr, 4);
console.log(arr);    // [1, 2, 3] — unchanged!
console.log(newArr); // [1, 2, 3, 4]
console.log(add(1, 2) === add(1, 2)); // Always true

💡 Pure functions are easier to test, debug, memoize, and parallelize.


Step 2: Immutability


Step 3: map, filter, reduce


Step 4: Currying


Step 5: Function Composition


Step 6: Point-Free Style

💡 Point-free style is about composition and reuse. Don't force it — readability matters more.


Step 7: Transducers Concept


Step 8: Capstone — Functional Data Processing

Run verification:

📸 Verified Output:


Summary

Concept
Description
Key Benefit

Pure functions

No side effects, deterministic

Testable, memoizable

Immutability

Never mutate, return new values

Predictable state

map

Transform each element

Declarative transformation

filter

Select elements by predicate

Declarative filtering

reduce

Accumulate to single value

Flexible aggregation

Currying

Function with partial application

Reusable function building

compose

Right-to-left function chain

Build complex from simple

pipe

Left-to-right function chain

Readable data pipeline

Point-free

Define ops without data args

Reusable combinators

Transducers

Composable, efficient transforms

Single-pass processing

Last updated