Lab 08: Functional Programming
Overview
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 trueStep 2: Immutability
Step 3: map, filter, reduce
Step 4: Currying
Step 5: Function Composition
Step 6: Point-Free Style
Step 7: Transducers Concept
Step 8: Capstone — Functional Data Processing
Summary
Concept
Description
Key Benefit
Last updated
