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. 命令模式的函數式實現
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);
結語 📝
函數式編程是一種強大的編程范式,掌握其進階特性可以幫助我們構建更加可靠和可維護的應用。通過本文,我們學習了:
- 函數式編程的進階概念和原理
- 高級函數式特性的實現
- 函數式數據結構
- 性能優化技巧
- 最佳實踐和設計模式
💡 學習建議:在實踐函數式編程時,要注意平衡純函數的理想和實際需求,合理使用副作用,同時要關注性能優化。
如果你覺得這篇文章有幫助,歡迎點贊收藏,也期待在評論區看到你的想法和建議!👇
終身學習,共同成長。
咱們下一期見
💻