JavaScript and TypeScript course ยท Module 9: Design Patterns and Architecture
Functional Programming in JavaScript/TypeScript
In this lesson6
Imagine a lab where the same DNA sample gives a different result depending on the time of day, because the analysis function peeks at a global variable. Functional programming cures this with pure functions, immutability and composition, which make code predictable, testable and easier to maintain.
Pure Functions
A pure function meets two conditions:
- Determinism - for the same arguments it always returns the same result
- No side effects - it does not modify external state and does not perform I/O operations
Examples of impure functions
Each of these functions breaks one of the conditions. Which one?
// Impure function - depends on external state
let tax = 0.23;
function calculatePrice(basePrice) {
return basePrice * (1 + tax); // Depends on external variable
}
// Impure function - modifies external state
let counter = 0;
function incrementCounter() {
counter++; // Side effect - modification of global variable
return counter;
}
// Impure function - side effect (I/O)
function greetUser(name) {
console.log(`Hello, ${name}!`); // Side effect - console output
return name;
}
// Impure function - nondeterminism
function getCurrentTimestamp() {
return Date.now(); // Different results for each invocation
}
// Impure function - modifies argument
function addItem(array, item) {
array.push(item); // Mutates the passed argument
return array;
}calculatePrice and getCurrentTimestamp break determinism, while the others have side effects: they change a global variable, write to the console or mutate the array they receive.
Examples of pure functions
The pure counterparts receive everything through arguments and return new values:
// Pure function - determinism and no side effects
function calculatePrice(basePrice: number, taxRate: number): number {
return basePrice * (1 + taxRate);
}
// Pure function - mathematical operation
function add(a: number, b: number): number {
return a + b;
}
// Pure function - data transformation
function formatFullName(firstName: string, lastName: string): string {
return `${firstName} ${lastName}`;
}
// Pure function - working with arrays (no mutation)
function addItem<T>(array: T[], item: T): T[] {
return [...array, item]; // Returns a new array
}
// Pure function - filtering
function filterEvenNumbers(numbers: number[]): number[] {
return numbers.filter(num => num % 2 === 0);
}
// Pure function - object transformation
interface User {
id: number;
name: string;
age: number;
}
function updateUserAge(user: User, newAge: number): User {
return {
...user, // Spread operator - copying existing properties
age: newAge // Overriding age
};
}
// Pure function - validation
function isValidEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
// Using pure functions
const products = [
{ name: 'Laptop', basePrice: 2000 },
{ name: 'Mouse', basePrice: 50 },
{ name: 'Keyboard', basePrice: 150 }
];
const TAX_RATE = 0.23;
const productsWithTax = products.map(product => ({
...product,
finalPrice: calculatePrice(product.basePrice, TAX_RATE)
}));
console.log(productsWithTax);The tax rate is a parameter, and addItem and updateUserAge return copies, so the originals stay untouched.
Benefits of pure functions
Determinism gives you two superpowers: tests with no world to set up, and memoization, which means remembering results:
// Easy to test - no external dependencies
function calculateDiscount(price: number, discountPercent: number): number {
return price * (discountPercent / 100);
}
// Unit test is simple and reliable
console.assert(calculateDiscount(100, 10) === 10);
console.assert(calculateDiscount(200, 25) === 50);
// Memoization - optimization thanks to determinism
function memoize<TArgs extends any[], TReturn>(
fn: (...args: TArgs) => TReturn
): (...args: TArgs) => TReturn {
const cache = new Map<string, TReturn>();
return (...args: TArgs): TReturn => {
const key = JSON.stringify(args);
if (cache.has(key)) {
console.log('Cache hit!');
return cache.get(key)!;
}
console.log('Computing...');
const result = fn(...args);
cache.set(key, result);
return result;
};
}
// Computationally expensive function
function fibonacci(n: number): number {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Memoized version
const memoizedFibonacci = memoize(fibonacci);
console.log(memoizedFibonacci(10)); // Computing... 55
console.log(memoizedFibonacci(10)); // Cache hit! 55memoize is a higher-order function: it takes another function as an argument or returns a function, and here it does both. map, filter and the Observer pattern's subscribe are higher-order functions too. The recursive calls inside fibonacci bypass the cache, though, so you only see the gain on a repeated call.
Immutability
Immutability means that objects and data structures are not modified after they are created. Instead, new versions with the changes applied are created, like in an archive where you never overwrite an old sample but add a new one.
Working with primitives
With primitives you get this for free, because strings and numbers in JavaScript are immutable by nature:
// Primitives in JavaScript are immutable by nature
let name = 'Jan';
let newName = name.toUpperCase(); // Creates a new string
console.log(name); // 'Jan' - original unchanged
console.log(newName); // 'JAN' - new valuetoUpperCase() does not change the name string, it returns a new one.
Working with arrays
Be careful with arrays, because some methods mutate the original. Compare both groups:
// Mutable operations (modify the original array)
const originalArray = [1, 2, 3];
originalArray.push(4); // Mutates
originalArray.pop(); // Mutates
originalArray.splice(1, 1); // Mutates
originalArray.sort(); // Mutates
// Immutable operations (create new arrays)
const numbers = [1, 2, 3];
// Adding elements
const withNewElement = [...numbers, 4];
const withElementAtStart = [0, ...numbers];
const withElementInMiddle = [...numbers.slice(0, 2), 2.5, ...numbers.slice(2)];
// Removing elements
const withoutFirst = numbers.slice(1);
const withoutLast = numbers.slice(0, -1);
const withoutMiddle = numbers.filter((_, index) => index !== 1);
// Modifying elements
const doubled = numbers.map(x => x * 2);
const incremented = numbers.map(x => x + 1);
// Sorting
const sorted = [...numbers].sort();
const reverseSorted = [...numbers].sort((a, b) => b - a);
console.log('Original array:', numbers); // [1, 2, 3]
console.log('Doubled:', doubled); // [2, 4, 6]
console.log('Sorted:', sorted); // [1, 2, 3]
// Advanced immutable operations
function updateArrayElement<T>(
array: T[],
index: number,
newValue: T
): T[] {
return array.map((item, i) => i === index ? newValue : item);
}
function moveArrayElement<T>(
array: T[],
fromIndex: number,
toIndex: number
): T[] {
const result = [...array];
const [removed] = result.splice(fromIndex, 1);
result.splice(toIndex, 0, removed);
return result;
}
const fruits = ['apple', 'banana', 'cherry'];
const updatedFruits = updateArrayElement(fruits, 1, 'blueberry');
const movedFruits = moveArrayElement(fruits, 0, 2);
console.log('Original:', fruits); // ['apple', 'banana', 'cherry']
console.log('Updated:', updatedFruits); // ['apple', 'blueberry', 'cherry']
console.log('Moved:', movedFruits); // ['banana', 'cherry', 'apple']The rule: push, pop, splice and sort change the array, while spread, slice, map and filter return a new one. Note that sort() without a compare function sorts elements as strings ([10, 9, 1].sort() gives [1, 10, 9]), and since ES2023 you have the non-mutating toSorted(), toReversed(), toSpliced() and with().
Working with objects
We copy objects with the spread operator. With nesting, we copy every level we change:
// Mutable operations on objects
const user = { id: 1, name: 'Jan', age: 30 };
user.age = 31; // Mutates
user.email = 'jan@example.com'; // Mutates
delete user.name; // Mutates
// Immutable operations on objects
const originalUser = { id: 1, name: 'Jan', age: 30 };
// Updating properties
const olderUser = { ...originalUser, age: 31 };
// Adding properties
const userWithEmail = { ...originalUser, email: 'jan@example.com' };
// Removing properties
const { name, ...userWithoutName } = originalUser;
// Nested updates
interface Address {
street: string;
city: string;
country: string;
}
interface UserWithAddress {
id: number;
name: string;
address: Address;
}
const userWithAddress: UserWithAddress = {
id: 1,
name: 'Jan',
address: {
street: 'Main St',
city: 'Warsaw',
country: 'Poland'
}
};
// Mutable nested update
userWithAddress.address.city = 'Krakow'; // Mutates
// Immutable nested update
const userInKrakow = {
...userWithAddress,
address: {
...userWithAddress.address,
city: 'Krakow'
}
};
// Helper functions for immutable operations
function updateProperty<T, K extends keyof T>(
obj: T,
key: K,
value: T[K]
): T {
return { ...obj, [key]: value };
}
function updateNestedProperty<T>(
obj: T,
path: string[],
value: any
): T {
if (path.length === 1) {
return { ...obj, [path[0]]: value };
}
const [firstKey, ...restPath] = path;
return {
...obj,
[firstKey]: updateNestedProperty(obj[firstKey as keyof T], restPath, value)
};
}
// Using helper functions
const updatedUser = updateProperty(originalUser, 'age', 35);
const userInGdansk = updateNestedProperty(
userWithAddress,
['address', 'city'],
'Gdansk'
);
console.log('Original:', originalUser); // { id: 1, name: 'Jan', age: 30 }
console.log('Updated:', updatedUser); // { id: 1, name: 'Jan', age: 35 }Spread makes a shallow copy, which is why we unpack address separately. In TypeScript (strict) the lines with user.email and delete user.name will not even compile, because the type has no email field and delete requires an optional field.
Immutability libraries
Copying deep structures by hand gets tiring, which is why Immer exists: you write code that looks like it mutates a draft, and the library returns a new state:
// Immer - a library that simplifies working with immutable structures
// npm install immer
import { produce } from 'immer';
interface Todo {
id: number;
text: string;
completed: boolean;
}
const todos: Todo[] = [
{ id: 1, text: 'Learn JavaScript', completed: false },
{ id: 2, text: 'Learn TypeScript', completed: true },
{ id: 3, text: 'Learn React', completed: false }
];
// With Immer - looks like mutation, but creates new state
const updatedTodos = produce(todos, draft => {
const todo = draft.find(t => t.id === 1);
if (todo) {
todo.completed = true;
}
});
const todosWithNewItem = produce(todos, draft => {
draft.push({
id: 4,
text: 'Learn functional programming',
completed: false
});
});
console.log('Original todos:', todos);
console.log('Updated todos:', updatedTodos);
console.log('Todos with new item:', todosWithNewItem);
// Advanced example with nested structures
interface Project {
id: number;
name: string;
todos: Todo[];
members: string[];
}
const project: Project = {
id: 1,
name: 'Project A',
todos: todos,
members: ['Jan', 'Anna']
};
const updatedProject = produce(project, draft => {
// Add new member
draft.members.push('Piotr');
// Mark all todos as completed
draft.todos.forEach(todo => {
todo.completed = true;
});
// Change project name
draft.name = 'Project A - Completed';
});
console.log('Original project:', project);
console.log('Updated project:', updatedProject);The originals stay untouched, and the unchanged parts are shared. For deeply nested state I recommend Immer.
Currying
Currying is the technique of transforming a function that takes multiple arguments into a series of functions, each taking a single argument.
Basic currying
Here is the same multiplication function in its classic and its curried form:
// Function with multiple arguments
function multiply(a: number, b: number, c: number): number {
return a * b * c;
}
console.log(multiply(2, 3, 4)); // 24
// Curried version
function curriedMultiply(a: number) {
return function(b: number) {
return function(c: number) {
return a * b * c;
};
};
}
console.log(curriedMultiply(2)(3)(4)); // 24
// Curried version with arrow functions
const curriedMultiplyArrow = (a: number) => (b: number) => (c: number) => a * b * c;
console.log(curriedMultiplyArrow(2)(3)(4)); // 24
// Partial application
const multiplyBy2 = curriedMultiply(2);
const multiplyBy2And3 = multiplyBy2(3);
console.log(multiplyBy2And3(4)); // 24
console.log(multiplyBy2And3(5)); // 30Each call returns another function until the last argument arrives. multiplyBy2 is partial application: it remembers the first argument thanks to a closure.
Practical applications of currying
The real power shows up when the first arguments are configuration and the last one is data:
// Logging system with currying
type LogLevel = 'info' | 'warn' | 'error';
const logger = (level: LogLevel) => (message: string) => (context?: object) => {
const timestamp = new Date().toISOString();
const logEntry = {
level,
message,
timestamp,
context
};
console.log(JSON.stringify(logEntry, null, 2));
};
// Creating specialized loggers
const infoLogger = logger('info');
const errorLogger = logger('error');
const warnLogger = logger('warn');
// Usage
infoLogger('Application started')();
errorLogger('Database connection error')({ database: 'PostgreSQL' });
warnLogger('High RAM usage')({ usage: '85%' });
// Validation system with currying
type Validator<T> = (value: T) => boolean;
const createValidator = <T>(predicate: (value: T) => boolean) =>
(errorMessage: string) =>
(value: T): { isValid: boolean; error?: string } => {
const isValid = predicate(value);
return isValid ? { isValid } : { isValid, error: errorMessage };
};
// Validation predicates
const isNotEmpty = (value: string) => value.trim().length > 0;
const isEmail = (value: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
const isMinLength = (minLength: number) => (value: string) => value.length >= minLength;
const isNumber = (value: string) => !isNaN(Number(value));
// Creating validators
const requiredValidator = createValidator(isNotEmpty)('Field is required');
const emailValidator = createValidator(isEmail)('Invalid email format');
const passwordValidator = createValidator(isMinLength(8))('Password must be at least 8 characters');
const ageValidator = createValidator(isNumber)('Age must be a number');
// Using validators
console.log(requiredValidator('Jan')); // { isValid: true }
console.log(requiredValidator('')); // { isValid: false, error: 'Field is required' }
console.log(emailValidator('jan@example.com')); // { isValid: true }
console.log(passwordValidator('123')); // { isValid: false, error: 'Password must be at least 8 characters' }
// API configuration system with currying
const apiCall = (baseUrl: string) =>
(endpoint: string) =>
(method: 'GET' | 'POST' | 'PUT' | 'DELETE') =>
(data?: any) => {
const config = {
url: `${baseUrl}${endpoint}`,
method,
data
};
console.log('API Call:', config);
// Here would be the actual API call
return Promise.resolve({ success: true, config });
};
// Configuration for different environments
const devApi = apiCall('https://dev-api.example.com');
const prodApi = apiCall('https://api.example.com');
// Specialized functions for different endpoints
const usersApi = devApi('/users');
const productsApi = devApi('/products');
// Specific operations
const getUsers = usersApi('GET');
const createUser = usersApi('POST');
const updateUser = usersApi('PUT');
// Usage
getUsers();
createUser({ name: 'Jan', email: 'jan@example.com' });
updateUser({ id: 1, name: 'Jan Kowalski' });Each of these functions is a small factory: createValidator produces validators, and apiCall produces API clients. The Factory pattern did the same with a class, for example DinoFactory with a create(type) method returning new Dinosaur(type), separating creation from use.
Automatic currying
The curry helper curries a function automatically, collecting arguments until there are as many as the function has parameters:
// Helper function for automatic currying
function curry<TArgs extends any[], TReturn>(
fn: (...args: TArgs) => TReturn
): (...args: any[]) => any {
return function curried(...args: any[]) {
if (args.length >= fn.length) {
return fn(...args as TArgs);
} else {
return function(...nextArgs: any[]) {
return curried(...args, ...nextArgs);
};
}
};
}
// Example of automatic currying usage
function sum(a: number, b: number, c: number, d: number): number {
return a + b + c + d;
}
const curriedSum = curry(sum);
// Various ways to call
console.log(curriedSum(1, 2, 3, 4)); // 10
console.log(curriedSum(1)(2)(3)(4)); // 10
console.log(curriedSum(1, 2)(3, 4)); // 10
console.log(curriedSum(1)(2, 3)(4)); // 10
// Partial application
const add5 = curriedSum(5);
const add5And10 = add5(10);
const add5And10And15 = add5And10(15);
console.log(add5And10And15(20)); // 50
// Example with filtering and sorting
function filterAndSort<T>(
predicate: (item: T) => boolean,
compareKey: keyof T,
array: T[]
): T[] {
return array
.filter(predicate)
.sort((a, b) => {
if (a[compareKey] < b[compareKey]) return -1;
if (a[compareKey] > b[compareKey]) return 1;
return 0;
});
}
const curriedFilterAndSort = curry(filterAndSort);
interface Product {
id: number;
name: string;
price: number;
category: string;
inStock: boolean;
}
const products: Product[] = [
{ id: 1, name: 'Laptop', price: 2000, category: 'Electronics', inStock: true },
{ id: 2, name: 'Mouse', price: 50, category: 'Electronics', inStock: false },
{ id: 3, name: 'Book', price: 25, category: 'Books', inStock: true },
{ id: 4, name: 'Keyboard', price: 150, category: 'Electronics', inStock: true }
];
// Specialized functions
const filterInStockSortByPrice = curriedFilterAndSort(
(product: Product) => product.inStock
)('price');
const filterElectronicsSortByName = curriedFilterAndSort(
(product: Product) => product.category === 'Electronics'
)('name');
console.log('Available products sorted by price:', filterInStockSortByPrice(products));
console.log('Electronics sorted by name:', filterElectronicsSortByName(products));curry relies on fn.length, which does not count a rest parameter or any parameters from the first one with a default value onward.
Function Composition
Function composition is combining simple functions into more complex ones by passing the result of one as the argument of the next, like the stages of a lab line.
Basic composition
Instead of nesting calls, we build a pipeline. compose runs functions from right to left, and pipe from left to right:
// Simple functions
const add = (x: number) => x + 1;
const multiply = (x: number) => x * 2;
const square = (x: number) => x * x;
// Without composition - nested calls
const result1 = square(multiply(add(5))); // ((5 + 1) * 2)^2 = 144
// compose function - executes functions from right to left
function compose<T>(...functions: Array<(arg: T) => T>) {
return (value: T): T => {
return functions.reduceRight((acc, fn) => fn(acc), value);
};
}
// pipe function - executes functions from left to right (more intuitive)
function pipe<T>(...functions: Array<(arg: T) => T>) {
return (value: T): T => {
return functions.reduce((acc, fn) => fn(acc), value);
};
}
// Using compose
const composedFunction = compose(square, multiply, add);
console.log(composedFunction(5)); // 144
// Using pipe (more readable)
const pipedFunction = pipe(add, multiply, square);
console.log(pipedFunction(5)); // 144
// Practical example - user data processing
interface User {
firstName: string;
lastName: string;
age: number;
email: string;
}
const users: User[] = [
{ firstName: 'Jan', lastName: 'Kowalski', age: 25, email: 'jan@example.com' },
{ firstName: 'Anna', lastName: 'Nowak', age: 30, email: 'anna@example.com' },
{ firstName: 'Piotr', lastName: 'Wisniewski', age: 22, email: 'piotr@example.com' }
];
// Helper functions
const filterAdults = (users: User[]) => users.filter(user => user.age >= 18);
const sortByAge = (users: User[]) => [...users].sort((a, b) => a.age - b.age);
const mapToFullNames = (users: User[]) =>
users.map(user => `${user.firstName} ${user.lastName}`);
// Composition
const processUsers = pipe(
filterAdults,
sortByAge,
mapToFullNames
);
const processedUsers = processUsers(users);
console.log(processedUsers); // ['Piotr Wisniewski', 'Jan Kowalski', 'Anna Nowak']Both variants give 144, but pipe reads in the order of execution, and that is the one I recommend. The catch: every step must return the same type, so mapToFullNames will cause a type error in TypeScript, even without strict mode.
Advanced composition with TypeScript
When the type changes along the way, every stage needs its own type parameter, as in compose3:
// Typed composition for different types
function compose2<A, B, C>(f: (b: B) => C, g: (a: A) => B) {
return (a: A): C => f(g(a));
}
function compose3<A, B, C, D>(
f: (c: C) => D,
g: (b: B) => C,
h: (a: A) => B
) {
return (a: A): D => f(g(h(a)));
}
// Example of typed composition usage
const parseNumber = (str: string): number => parseFloat(str);
const addTax = (price: number): number => price * 1.23;
const formatCurrency = (amount: number): string => `${amount.toFixed(2)} PLN`;
const processPrice = compose3(formatCurrency, addTax, parseNumber);
console.log(processPrice('100')); // '123.00 PLN'
// Validation system with composition
type ValidationResult = {
isValid: boolean;
errors: string[];
};
type Validator<T> = (value: T) => ValidationResult;
const combineValidators = <T>(...validators: Validator<T>[]): Validator<T> => {
return (value: T): ValidationResult => {
const results = validators.map(validator => validator(value));
return {
isValid: results.every(result => result.isValid),
errors: results.flatMap(result => result.errors)
};
};
};
// Individual validators
const isRequired: Validator<string> = (value: string) => ({
isValid: value.trim().length > 0,
errors: value.trim().length === 0 ? ['Field is required'] : []
});
const isEmail: Validator<string> = (value: string) => {
const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
return {
isValid,
errors: isValid ? [] : ['Invalid email format']
};
};
const minLength = (min: number): Validator<string> => (value: string) => {
const isValid = value.length >= min;
return {
isValid,
errors: isValid ? [] : [`Minimum ${min} characters required`]
};
};
// Composition of validators
const emailValidator = combineValidators(isRequired, isEmail);
const passwordValidator = combineValidators(isRequired, minLength(8));
console.log(emailValidator('jan@example.com')); // { isValid: true, errors: [] }
console.log(emailValidator('')); // { isValid: false, errors: ['Field is required', 'Invalid email format'] }
console.log(passwordValidator('123')); // { isValid: false, errors: ['Minimum 8 characters required'] }
// Data processing with composition
interface RawProduct {
name: string;
price: string;
description: string;
tags: string;
}
interface ProcessedProduct {
name: string;
price: number;
description: string;
tags: string[];
slug: string;
}
// Transformation functions
const parsePrice = (product: RawProduct): ProcessedProduct => ({
...product,
price: parseFloat(product.price),
tags: product.tags.split(','), // raw pieces, parseTags cleans them up
slug: ''
});
const parseTags = (product: ProcessedProduct): ProcessedProduct => ({
...product,
tags: product.tags.map(tag => tag.trim()).filter(tag => tag.length > 0)
});
const generateSlug = (product: ProcessedProduct): ProcessedProduct => ({
...product,
slug: product.name.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '')
});
const validateProduct = (product: ProcessedProduct): ProcessedProduct => {
if (product.price <= 0) {
throw new Error('Price must be greater than 0');
}
if (!product.name.trim()) {
throw new Error('Product name is required');
}
return product;
};
// Processing composition - parsePrice changes the type, so we call it before pipe
const processProduct = (raw: RawProduct): ProcessedProduct => pipe(
parseTags,
generateSlug,
validateProduct
)(parsePrice(raw));
const rawProduct: RawProduct = {
name: 'Super Laptop',
price: '2999.99',
description: 'The best laptop on the market',
tags: 'laptop, computer, electronics'
};
try {
const processed = processProduct(rawProduct);
console.log('Processed product:', processed);
} catch (error) {
console.error('Processing error:', (error as Error).message);
}combineValidators collects errors from all validators, and the type-changing step, parsePrice, is called before pipe.
Asynchronous composition
A pipeline also works with promises (Promise). Each step waits for the result of the previous one thanks to then:
// Composition for asynchronous functions
const composeAsync = <T>(...functions: Array<(arg: T) => Promise<T>>) => {
return (value: T): Promise<T> => {
return functions.reduceRight<Promise<T>>(
(acc, fn) => acc.then(fn),
Promise.resolve(value)
);
};
};
const pipeAsync = <T>(...functions: Array<(arg: T) => Promise<T>>) => {
return (value: T): Promise<T> => {
return functions.reduce<Promise<T>>(
(acc, fn) => acc.then(fn),
Promise.resolve(value)
);
};
};
// Example usage with API
interface ApiUser {
id: number;
name: string;
email: string;
}
interface EnrichedUser extends ApiUser {
avatar: string;
lastLogin: Date;
preferences: any;
}
// Asynchronous functions
const fetchUser = async (userId: number): Promise<ApiUser> => {
console.log(`Fetching user ${userId}`);
// API call simulation
return new Promise(resolve => {
setTimeout(() => {
resolve({
id: userId,
name: 'Jan Kowalski',
email: 'jan@example.com'
});
}, 100);
});
};
const enrichWithAvatar = async (user: ApiUser): Promise<EnrichedUser> => {
console.log('Enriching with avatar');
return new Promise(resolve => {
setTimeout(() => {
resolve({
...user,
avatar: `https://avatars.example.com/${user.id}`,
lastLogin: new Date(),
preferences: {}
});
}, 50);
});
};
const enrichWithPreferences = async (user: EnrichedUser): Promise<EnrichedUser> => {
console.log('Enriching with preferences');
return new Promise(resolve => {
setTimeout(() => {
resolve({
...user,
preferences: {
theme: 'dark',
language: 'pl',
notifications: true
}
});
}, 50);
});
};
// Asynchronous composition - enrichWithAvatar changes the type (ApiUser -> EnrichedUser),
// so we call it before the pipeline
const enrichUser = (user: ApiUser): Promise<EnrichedUser> =>
enrichWithAvatar(user).then(pipeAsync(enrichWithPreferences));
// Usage
async function main() {
try {
const user = await fetchUser(1);
const enrichedUser = await enrichUser(user);
console.log('Enriched user:', enrichedUser);
} catch (error) {
console.error('Error:', error);
}
}
main();reduce weaves the steps into a single promise chain, preserving the order.
Practical example - E-commerce system with functional programming
Finally, everything together: pure filters, an immutable cart, currying and pipe:
// Comprehensive example of functional programming application
// Data types
interface Product {
id: string;
name: string;
price: number;
category: string;
tags: string[];
inStock: boolean;
rating: number;
}
interface CartItem {
product: Product;
quantity: number;
}
interface Cart {
items: CartItem[];
discountCode?: string;
}
interface Order {
id: string;
items: CartItem[];
subtotal: number;
discount: number;
tax: number;
total: number;
timestamp: Date;
}
// Pure functions for products
const filterByCategory = (category: string) => (products: Product[]) =>
products.filter(product => product.category === category);
const filterByPriceRange = (min: number, max: number) => (products: Product[]) =>
products.filter(product => product.price >= min && product.price <= max);
const filterInStock = (products: Product[]) =>
products.filter(product => product.inStock);
const sortByPrice = (ascending: boolean = true) => (products: Product[]) =>
[...products].sort((a, b) => ascending ? a.price - b.price : b.price - a.price);
const sortByRating = (products: Product[]) =>
[...products].sort((a, b) => b.rating - a.rating);
// Cart functions
const addToCart = (product: Product, quantity: number) => (cart: Cart): Cart => {
const existingItemIndex = cart.items.findIndex(item => item.product.id === product.id);
if (existingItemIndex >= 0) {
return {
...cart,
items: cart.items.map((item, index) =>
index === existingItemIndex
? { ...item, quantity: item.quantity + quantity }
: item
)
};
}
return {
...cart,
items: [...cart.items, { product, quantity }]
};
};
const removeFromCart = (productId: string) => (cart: Cart): Cart => ({
...cart,
items: cart.items.filter(item => item.product.id !== productId)
});
const updateQuantity = (productId: string, newQuantity: number) => (cart: Cart): Cart => {
if (newQuantity <= 0) {
return removeFromCart(productId)(cart);
}
return {
...cart,
items: cart.items.map(item =>
item.product.id === productId
? { ...item, quantity: newQuantity }
: item
)
};
};
const applyDiscountCode = (discountCode: string) => (cart: Cart): Cart => ({
...cart,
discountCode
});
// Price calculation functions
const calculateItemTotal = (item: CartItem): number =>
item.product.price * item.quantity;
const calculateSubtotal = (items: CartItem[]): number =>
items.reduce((total, item) => total + calculateItemTotal(item), 0);
const calculateDiscount = (subtotal: number, discountCode?: string): number => {
const discountRates: Record<string, number> = {
'SAVE10': 0.1,
'SAVE20': 0.2,
'STUDENT': 0.15
};
if (!discountCode || !discountRates[discountCode]) {
return 0;
}
return subtotal * discountRates[discountCode];
};
const calculateTax = (amount: number, taxRate: number = 0.23): number =>
amount * taxRate;
const calculateTotal = (subtotal: number, discount: number, tax: number): number =>
subtotal - discount + tax;
// Composition for order processing
const processOrder = (cart: Cart): Order => {
const subtotal = calculateSubtotal(cart.items);
const discount = calculateDiscount(subtotal, cart.discountCode);
const taxableAmount = subtotal - discount;
const tax = calculateTax(taxableAmount);
const total = calculateTotal(subtotal, discount, tax);
return {
id: 'order_' + Math.random().toString(36).slice(2, 11),
items: cart.items,
subtotal,
discount,
tax,
total,
timestamp: new Date()
};
};
// Search functions with composition
const searchProducts = (
query: string,
category?: string,
priceRange?: { min: number; max: number },
sortBy: 'price' | 'rating' = 'rating'
) => (products: Product[]): Product[] => {
const searchByName = (products: Product[]) =>
products.filter(product =>
product.name.toLowerCase().includes(query.toLowerCase()) ||
product.tags.some(tag => tag.toLowerCase().includes(query.toLowerCase()))
);
const filters = [
searchByName,
filterInStock
];
if (category) {
filters.push(filterByCategory(category));
}
if (priceRange) {
filters.push(filterByPriceRange(priceRange.min, priceRange.max));
}
const sorter = sortBy === 'price' ? sortByPrice() : sortByRating;
return pipe(...filters, sorter)(products);
};
// Example usage
const products: Product[] = [
{
id: '1',
name: 'Laptop Gaming',
price: 3500,
category: 'electronics',
tags: ['gaming', 'laptop', 'high-performance'],
inStock: true,
rating: 4.8
},
{
id: '2',
name: 'Gaming Mouse',
price: 150,
category: 'electronics',
tags: ['gaming', 'mouse', 'rgb'],
inStock: true,
rating: 4.5
},
{
id: '3',
name: 'JavaScript Book',
price: 89,
category: 'books',
tags: ['programming', 'javascript', 'learning'],
inStock: false,
rating: 4.9
}
];
// Creating cart functionally
const emptyCart: Cart = { items: [] };
const myCart = pipe(
addToCart(products[0], 1),
addToCart(products[1], 2),
applyDiscountCode('SAVE10')
)(emptyCart);
console.log('Cart:', myCart);
// Processing the order
const order = processOrder(myCart);
console.log('Order:', order);
// Searching products
const searchGaming = searchProducts('gaming', 'electronics', undefined, 'price');
const gamingProducts = searchGaming(products);
console.log('Gaming products:', gamingProducts);
// Partial application: the product is fixed, the quantity comes later
const addLaptopToCart = (quantity: number) => addToCart(products[0], quantity);
const addMouseToCart = (quantity: number) => addToCart(products[1], quantity);
const cartWithLaptop = addLaptopToCart(1)(emptyCart);
const cartWithBoth = addMouseToCart(2)(cartWithLaptop);
console.log('Cart with laptop and mouse:', cartWithBoth);The cart is never modified: every operation returns a new version.
Summary of functional programming
- Pure functions - predictability and ease of testing
- Immutability - safety and no side effects
- Currying - flexibility and reusability
- Composition - building complex logic from simple elements
You gain predictable code, easy unit tests, better conditions for parallel processing and fewer bugs caused by state mutation. The functional style shines in data transformations, heavy computations, systems that require high reliability and code you test often. In the editor below you will build a dinosaur registry, and in the next lesson pure functions come back as reducers.
"A pure function is a lab with closed doors: arguments go in, a result comes out," says Dr. Rex.
Code for this lesson: index.js
// Factory pattern - Dinosaur Registry
// Exercise: Implement a dinosaur factory and registry
class Dinosaur {
constructor(name, species, diet) {
this.name = name;
this.species = species;
this.diet = diet;
this.health = 100;
}
getInfo() {
return this.name + " (" + this.species + ") - " + this.diet;
}
}
class DinosaurRegistry {
constructor() {
this.dinosaurs = [];
}
// Implement the methods:
// create(name, species, diet) - creates and registers a dinosaur
// findBySpecies(species) - searches by species
// getAll() - returns all
create(name, species, diet) {
// Your code here
}
findBySpecies(species) {
// Your code here
}
}
const registry = new DinosaurRegistry();
console.log("Dinosaur registry ready");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. When is it best to use the Observer pattern?
2. What is a higher-order function?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
The index.js file has a DinosaurRegistry class with register, update and find methods. Fill in the blanks: ___BLANK1___ copies all fields of the old record into the new object (as in the immutability lesson), ___BLANK2___ is the array method that keeps only the matching records, and ___BLANK3___ is the array method that returns true only when the record matches every criterion. update should return a new object and leave the old one unchanged, and find({ zone: 'A', species: 'T-Rex' }) only the records that match both conditions.
- Click in order
Arrange the elements of a simple factory (Factory pattern) in the correct order:
- Code editor
The index.js file has a SecuritySystem class with sensors and observers (Observer pattern). Fill in the blanks: ___BLANK1___ is the array method that adds the observer in subscribe, ___BLANK2___ is the observer method that notify calls with the alert, and ___BLANK3___ is the comparison operator that gives an alert only to a sensor whose reading is greater than its threshold (a reading equal to the threshold is not an alarm). checkAlerts should return alerts { sensorId, zone, value } and notify all observers about each of them, and triggerEmergencyProtocol(reason) should turn on emergency mode and send the observers the alert { type: 'emergency', reason }.