Bootstrap

JavaScript系列(71)--函数式编程进阶详解

JavaScript函数式编程进阶详解 🎯

今天,让我们深入探讨JavaScript函数式编程的进阶内容。函数式编程是一种强大的编程范式,它通过使用纯函数和不可变数据来构建可预测和可维护的应用程序。

函数式编程进阶概念 🌟

💡 小知识:函数式编程的核心是通过函数组合来构建程序,避免状态共享和数据突变。高阶函数式编程更关注函数组合、柯里化、函子和monad等高级概念。

高级函数式特性实现 📊

// 1. 函数组合
const compose = (...fns) => x => 
    fns.reduceRight((acc, fn) => fn(acc), x);

const pipe = (...fns) => x => 
    fns.reduce((acc, fn) => fn(acc), x);

// 带错误处理的函数组合
const safeCompose = (...fns) => x => {
    try {
        return Either.right(fns.reduceRight((acc, fn) => fn(acc), x));
    } catch (error) {
        return Either.left(error);
    }
};

// 2. 柯里化和偏函数应用
const curry = (fn) => {
    const arity = fn.length;
    
    return function curried(...args) {
        if (args.length >= arity) {
            return fn.apply(this, args);
        }
        
        return function(...moreArgs) {
            return curried.apply(this, args.concat(moreArgs));
        };
    };
};

// 偏函数应用
const partial = (fn, ...presetArgs) => 
    (...laterArgs) => fn(...presetArgs, ...laterArgs);

// 3. 函子实现
class Functor {
    constructor(value) {
        this._value = value;
    }
    
    map(fn) {
        return new Functor(fn(this._value));
    }
    
    static of(value) {
        return new Functor(value);
    }
}

// Maybe函子
class Maybe extends Functor {
    map(fn) {
        return this._value === null || this._value === undefined
            ? Maybe.of(null)
            : Maybe.of(fn(this._value));
    }
    
    getOrElse(defaultValue) {
        return this._value === null || this._value === undefined
            ? defaultValue
            : this._value;
    }
}

// Either函子
class Either {
    static left(value) {
        return new Left(value);
    }
    
    static right(value) {
        return new Right(value);
    }
}

class Left extends Either {
    constructor(value) {
        super();
        this._value = value;
    }
    
    map() {
        return this;
    }
    
    getOrElse(defaultValue) {
        return defaultValue;
    }
}

class Right extends Either {
    constructor(value) {
        super();
        this._value = value;
    }
    
    map(fn) {
        return Either.right(fn(this._value));
    }
    
    getOrElse() {
        return this._value;
    }
}

函数式数据结构 🚀

// 1. 不可变列表
class List {
    constructor(head, tail = null) {
        this.head = head;
        this.tail = tail;
    }
    
    static of(...items) {
        return items.reduceRight(
            (acc, item) => new List(item, acc),
            null
        );
    }
    
    map(fn) {
        return new List(
            fn(this.head),
            this.tail ? this.tail.map(fn) : null
        );
    }
    
    filter(predicate) {
        if (!predicate(this.head)) {
            return this.tail ? this.tail.filter(predicate) : null;
        }
        return new List(
            this.head,
            this.tail ? this.tail.filter(predicate) : null
        );
    }
    
    reduce(fn, initial) {
        const result = fn(initial, this.head);
        return this.tail
            ? this.tail.reduce(fn, result)
            : result;
    }
}

// 2. 不可变树
class Tree {
    constructor(value, left = null, right = null) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
    
    map(fn) {
        return new Tree(
            fn(this.value),
            this.left ? this.left.map(fn) : null,
            this.right ? this.right.map(fn) : null
        );
    }
    
    fold(fn, initial) {
        const leftResult = this.left
            ? this.left.fold(fn, initial)
            : initial;
        const rightResult = this.right
            ? this.right.fold(fn, leftResult)
            : leftResult;
        return fn(rightResult, this.value);
    }
}

// 3. 延迟求值序列
class LazySequence {
    constructor(generator) {
        this.generator = generator;
    }
    
    static of(...items) {
        return new LazySequence(function* () {
            yield* items;
        });
    }
    
    map(fn) {
        const self = this;
        return new LazySequence(function* () {
            for (const item of self.generator()) {
                yield fn(item);
            }
        });
    }
    
    filter(predicate) {
        const self = this;
        return new LazySequence(function* () {
            for (const item of self.generator()) {
                if (predicate(item)) {
                    yield item;
                }
            }
        });
    }
    
    take(n) {
        const self = this;
        return new LazySequence(function* () {
            let count = 0;
            for (const item of self.generator()) {
                if (count >= n) break;
                yield item;
                count++;
            }
        });
    }
    
    toArray() {
        return [...this.generator()];
    }
}

性能优化实现 ⚡

// 1. 记忆化优化
const memoize = (fn) => {
    const cache = new Map();
    
    return (...args) => {
        const key = JSON.stringify(args);
        if (cache.has(key)) {
            return cache.get(key);
        }
        
        const result = fn(...args);
        cache.set(key, result);
        return result;
    };
};

// 带有LRU缓存的记忆化
class LRUCache {
    constructor(maxSize) {
        this.maxSize = maxSize;
        this.cache = new Map();
    }
    
    get(key) {
        const item = this.cache.get(key);
        if (item) {
            // 更新访问顺序
            this.cache.delete(key);
            this.cache.set(key, item);
        }
        return item;
    }
    
    set(key, value) {
        if (this.cache.has(key)) {
            this.cache.delete(key);
        } else if (this.cache.size >= this.maxSize) {
            // 删除最久未使用的项
            const firstKey = this.cache.keys().next().value;
            this.cache.delete(firstKey);
        }
        this.cache.set(key, value);
    }
}

// 2. 尾递归优化
const trampoline = fn => (...args) => {
    let result = fn(...args);
    while (typeof result === 'function') {
        result = result();
    }
    return result;
};

// 3. 批处理优化
class BatchProcessor {
    constructor(batchSize = 1000) {
        this.batchSize = batchSize;
        this.batch = [];
    }
    
    add(item) {
        this.batch.push(item);
        if (this.batch.length >= this.batchSize) {
            this.process();
        }
    }
    
    process() {
        if (this.batch.length === 0) return;
        
        const result = this.batch.reduce((acc, item) => {
            // 处理逻辑
            return acc;
        }, []);
        
        this.batch = [];
        return result;
    }
}

最佳实践建议 💡

  1. 函数式设计模式
// 1. 命令模式的函数式实现
const createCommand = (execute, undo) => ({
    execute,
    undo
});

const composeCommands = (...commands) => ({
    execute: () => commands.forEach(cmd => cmd.execute()),
    undo: () => commands.reverse().forEach(cmd => cmd.undo())
});

// 2. 观察者模式的函数式实现
const createObservable = () => {
    const observers = new Set();
    
    return {
        subscribe: observer => {
            observers.add(observer);
            return () => observers.delete(observer);
        },
        notify: value => observers.forEach(observer => observer(value))
    };
};

// 3. 策略模式的函数式实现
const strategies = new Map([
    ['add', (a, b) => a + b],
    ['subtract', (a, b) => a - b],
    ['multiply', (a, b) => a * b],
    ['divide', (a, b) => a / b]
]);

const executeStrategy = (name, ...args) =>
    (strategies.get(name) || (() => null))(...args);

结语 📝

函数式编程是一种强大的编程范式,掌握其进阶特性可以帮助我们构建更加可靠和可维护的应用。通过本文,我们学习了:

  1. 函数式编程的进阶概念和原理
  2. 高级函数式特性的实现
  3. 函数式数据结构
  4. 性能优化技巧
  5. 最佳实践和设计模式

💡 学习建议:在实践函数式编程时,要注意平衡纯函数的理想和实际需求,合理使用副作用,同时要关注性能优化。


如果你觉得这篇文章有帮助,欢迎点赞收藏,也期待在评论区看到你的想法和建议!👇

终身学习,共同成长。

咱们下一期见

💻

;