Funktionale Programmierungsparadigmen

Geschätzte Lektüre: 3 Minuten 344 Ansichten

Funktionale Programmierung gewinnt in modernen Sprachen zunehmend an Bedeutung, da sie Vorteile wie Unveränderlichkeit, Seiteneffektfreiheit und bessere Parallelisierbarkeit bietet. JavaScript hat funktionale Konstrukte schrittweise adoptiert:

// Higher-Order Functions und Currying
const curry = (fn) => (...args) => 
    args.length >= fn.length 
        ? fn(...args) 
        : curry(fn.bind(null, ...args));

const multiply = (a, b, c) => a * b * c;
const curriedMultiply = curry(multiply);

const multiplyBy2 = curriedMultiply(2);
const multiplyBy2And3 = multiplyBy2(3);
console.log(multiplyBy2And3(4)); // 24

// Funktionale Komposition
const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);
const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);

const addOne = x => x + 1;
const double = x => x * 2;
const square = x => x * x;

const complexOperation = pipe(addOne, double, square);
console.log(complexOperation(3)); // ((3 + 1) * 2)² = 64

// Immutability und Pure Functions
const updateUser = (user, updates) => ({
    ...user,
    ...updates,
    updatedAt: new Date()
});

// Monads für Fehlerbehandlung (Optional Pattern)
class Maybe {
    constructor(value) {
        this.value = value;
    }
    
    static of(value) {
        return new Maybe(value);
    }
    
    static nothing() {
        return new Maybe(null);
    }
    
    map(fn) {
        return this.value === null ? Maybe.nothing() : Maybe.of(fn(this.value));
    }
    
    flatMap(fn) {
        return this.value === null ? Maybe.nothing() : fn(this.value);
    }
    
    getOrElse(defaultValue) {
        return this.value === null ? defaultValue : this.value;
    }
}

// Verwendung des Maybe-Monads
const safeParseInt = (str) => {
    const parsed = parseInt(str);
    return isNaN(parsed) ? Maybe.nothing() : Maybe.of(parsed);
};

const result = safeParseInt("42")
    .map(x => x * 2)
    .map(x => x + 10)
    .getOrElse(0);

console.log(result); // 94
Dieses Dokument teilen

Funktionale Programmierungsparadigmen

Oder Link kopieren

INHALT

Abonnieren

×
Cancel