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

server/2025/2/13 13:28:10/

JavaScript函数式编程进阶详解 🎯

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

函数式编程进阶概念 🌟

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

高级函数式特性实现 📊

javascript">// 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;}
}

函数式数据结构 🚀

javascript">// 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()];}
}

性能优化实现 ⚡

javascript">// 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. 函数式设计模式
javascript">// 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. 最佳实践和设计模式

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


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

终身学习,共同成长。

咱们下一期见

💻


http://www.ppmy.cn/server/167341.html

相关文章

从零到一:基于Rook构建云原生Ceph存储的全面指南(上)

文章目录 一.Rook简介二.Rook与Ceph架构2.1 Rook结构体系2.2 Rook包含组件1)Rook Operator2)Rook Discover3)Rook Agent 2.3 Rook与kubernetes结合的架构图如下2.4 ceph特点2.5 ceph架构2.6 ceph组件 三.Rook部署Ceph集群3.1 部署条件3.3 获取…

Redis主从架构同步原理

主从复制概述 有了AOF和RDB,如果Redis发生了宕机,它们可以分别通过回放日志和重新读入RDB文件的方式恢复数据,从而保证尽量少丢失数据,提升可靠性。但是如果Redis实例宕机了,就无法提供服务了。 既然⼀台宕机了⽆法提…

go 语言设置 商城首页

1:前端传递的数据结构: {"page_type": 10,"page_name": "商城首页","page_data": {"page": {"params": {"name": "商城首页","title": "萤火商城2.0","…

数据库的基本概念

在当今的信息时代,数据已成为企业乃至整个社会的重要资产。如何有效地存储、管理和利用这些数据成为了技术发展的关键领域之一。数据库系统作为数据管理的核心工具,在软件开发、数据分析等多个方面扮演着不可或缺的角色。本文将带你了解数据库的一些基本…

Redis 常见面试题汇总(持续更新)

文章目录 01、Redis 支持哪些数据类型?02、谈谈对 Redis 的 AOF 机制的 rewrite 模式的理解?03、请列举几个 Redis 常见性能问题和解决方案04、Redis 使用的最大内存是多少?内存数据淘汰策略有哪些?05、请谈谈 Redis 的同步机制。…

DeepSeek的蒸馏技术:让模型推理更快

DeepSeek系列模型,如DeepSeek-R1-Distill-Qwen-7B,采用了知识蒸馏(Knowledge Distillation)技术,这是一种强大的模型压缩和优化方法。通过蒸馏,DeepSeek模型在保持甚至提升性能的同时,实现了更快…

DeepSeek 中的 GRPO 算法全面解析

摘要: 为特定任务调整大型语言模型 (LLM) 通常涉及通过使用人类反馈 (RLHF) 的强化学习对偏好数据进行微调。 虽然这些数据通常来自不同的标注者群体(例如,不同的文化背景、种族、公司团队等),但传统的 RLHF 方法采用“一刀切”的方法,即,它们不加区分地假设并优化一个单…

【小蓝的旅行计划——带悔贪心(优先队列)、线段树】

题目 动态规划代码 #include <bits/stdc.h> using namespace std; const int N 1e3 10; int f[N][N]; int main() {memset(f, 0x3f, sizeof f);int n, m;cin >> n >> m;f[0][m] 0;for (int i 1; i < n; i){int d, w, l;cin >> d >> w &…