Part 1: Pure Functions and Immutability - Predictable Code
Introduction
What is a Pure Function?
Impure Function
// Impure - depends on external state
let discount = 0.1;
function calculatePrice(basePrice: number): number {
return basePrice * (1 - discount); // Depends on external 'discount'
}
console.log(calculatePrice(100)); // 90
discount = 0.2; // Someone changed discount!
console.log(calculatePrice(100)); // 80 - same input, different output!Pure Function
Side Effects
Managing Side Effects
Immutability
The Problem with Mutations
Immutable Approach
Real Example: User Profile Updates
Real Example: Shopping Cart
Immutable Array Operations
Immutable Object Updates
Real Example: API Response Transformation
Benefits of Pure Functions
1. Easy Testing
2. Easy Debugging
3. Memoization
4. Parallelization
Best Practices
1. Make Dependencies Explicit
2. Avoid Mutating Arguments
3. Use TypeScript readonly
4. Separate Pure and Impure
What's Next
PreviousFunctional Programming 101NextPart 2: Higher-Order Functions and Composition - Building Pipelines
Last updated