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. 最佳实践和设计模式

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


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

终身学习,共同成长。

咱们下一期见

💻

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/895340.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

postman登录cookie设置

1.设置环境变量, 定义变量存放共享的登录信息 如Cookie 2.登录接口编码test脚本获取cookie信息 let jsessionidCookie pm.cookies.get("JSESSIONID");if (jsessionidCookie) {let cookie "JSESSIONID" jsessionidCookie "; Admin-Tok…

c/c++蓝桥杯经典编程题100道(21)背包问题

背包问题 ->返回c/c蓝桥杯经典编程题100道-目录 目录 背包问题 一、题型解释 二、例题问题描述 三、C语言实现 解法1:0-1背包(基础动态规划,难度★) 解法2:0-1背包(空间优化版,难度★…

讲解下MySql的外连接查询在SpringBoot中的使用情况

在Spring Boot中使用MySQL的外连接查询时,通常通过JPA、MyBatis或JDBC等持久层框架来实现。外连接查询主要用于从多个表中获取数据,即使某些表中没有匹配的记录。外连接分为左外连接(LEFT JOIN)、右外连接(RIGHT JOIN&…

【大模型知识点】什么是KV Cache?为什么要使用KV Cache?使用KV Cache会带来什么问题?

1.什么是KV Cache?为什么要使用KV Cache? 理解此问题,首先需理解自注意机制的计算和掩码自注意力机制,在Decoder架构的模型中,每生成一个新的token,便需要重新执行一次自注意力计算,这个过程中…

【STM32】HAL库Host MSC读写外部U盘及FatFS文件系统的USB Disk模式

【STM32】HAL库Host MSC读写外部U盘及FatFS文件系统的USB Disk模式 在先前 分别介绍了FatFS文件系统和USB虚拟U盘MSC配置 前者通过MCU读写Flash建立文件系统 后者通过MSC连接电脑使其能够被操作 这两者可以合起来 就能够实现同时在MCU、USB中操作Flash的文件系统 【STM32】通过…

1.1计算机的发展

一、计算机系统的概念 1、计算机系统软件+硬件 软件:由具有各种特殊功能的程序组成。 硬件:计算机的实体。如:主机、外设等。 硬件决定了计算机系统的上限,软件决定了硬件性能发挥了多少。 2、软件 软件有系统软…

本地生活服务平台开发进入发展热潮

本地生活服务平台:当下的发展热潮 本地生活服务平台开发模式 在当今数字化时代,本地生活服务平台开发已成为人们日常生活中不可或缺的一部分。只需动动手指,打开手机上的 APP,就能轻松满足各类生活需求。像某团、饿XX这样的平台&a…

LSTM变种模型

GRU GRU简介 门控循环神经网络 (Gated Recurrent Neural Network,GRNN) 的提出,旨在更好地捕捉时间序列中时间步距离较大的依赖关系。它通过可学习的门来控制信息的流动。其中,门控循环单元 (Gated Recurrent Unit , GRU) 是…

详解tensorflow的tensor和Python list及Numpy矩阵的区别

TensorFlow中的张量(tensor)、Python列表和NumPy矩阵在数据结构和功能上有一些显著的区别。以下是它们的详细介绍及代码示例。 1、Python List 定义:Python列表是一种内置的数据结构,可以存储不同类型的对象,包括数字…

多模态模型详解

多模态模型是什么 多模态模型是一种能够处理和理解多种数据类型(如文本、图像、音频、视频等)的机器学习模型,通过融合不同模态的信息来提升任务的性能。其核心在于利用不同模态之间的互补性,增强模型的鲁棒性和准确性。 如何融合…

微服务与网关

什么是网关 背景 单体项目中,前端只用访问指定的一个端口8080,就可以得到任何想要的数据 微服务项目中,ip是不断变化的,端口是多个的 解决方案:网关 网关:就是网络的关口,负责请求的路由、转发…

二分算法篇:二分答案法的巧妙应用

二分算法篇:二分答案法的巧妙应用 那么看到二分这两个字想必我们一定非常熟悉,那么在大学期间的c语言的教学中会专门讲解二分查找,那么我们来简单回顾一下二分查找算法,我们知道二分查找是在一个有序的序列中寻找一个数在这个序列…

XZ_Mac电脑上本地化部署DeepSeek的详细步骤

根据您的需求,以下是Mac电脑上本地化部署DeepSeek的详细步骤: 一、下载并安装Ollama 访问Ollama官网: 打开浏览器,访问 Ollama官网。 下载Ollama: 在官网中找到并点击“Download”按钮,选择适合Mac系统的…

C# OpenCV机器视觉:模仿Halcon各向异性扩散滤波

在一个充满创意与挑战的图像处理工作室里,阿强是一位热情的图像魔法师。他总是在追求更加出色的图像效果,然而,传统的图像处理方法有时候并不能满足他的需求。 有一天,阿强听说了 Halcon 中的各向异性扩散滤波功能,它…

实现:多活的基础中间件

APIRouter : 路由分发服务 API Router 是一个 HTTP 反向代理和负载均衡器,部署在公有云中作为 HTTP API 流量的入口,它能识别 出流量的归属 shard ,并根据 shard 将流量转发到对应的 ezone 。 API Router 支持多种路由键&am…

Python3连接MongoDB并写入数据

个人博客地址:Python3连接MongoDB并写入数据 | 一张假钞的真实世界 安装PyMongo $ pip3 install pymongo Successfully installed pymongo-3.7.2 连接MongoDB并且批量插入操作 #!/usr/bin/python3import mysql.connector import gzip import json from pymongo …

Python 操作 MongoDB 教程

一、引言 在当今数字化时代,数据的存储和管理至关重要。传统的关系型数据库在处理一些复杂场景时可能会显得力不从心,而 NoSQL 数据库应运而生。MongoDB 作为一款开源的、面向文档的 NoSQL 数据库,凭借其高性能、高可扩展性和灵活的数据模型…

使用 Python-pptx 库提取 PPTX 文件中的结构与文字

是的,使用 python-pptx 库是提取 PPTX 文件中结构和文字的理想选择,原因如下: 专门处理 PPTX 格式 python-pptx 是一个专门为处理 PPTX 文件(.pptx 格式)而设计的 Python 库。 它可以读取和操作 PPTX 文件的内部结构…

DeepSeek本地化部署

DeepSeek本地化部署 本教程为一键式部署,适合于mac、ubuntu、windows。【开源地址】 环境要求 nodejs > 18Python > 3.10.12 步骤一:安装ollama客户端 官网直接安装,ollama官网。安装完成后使用命令:ollama -h&#xf…

驱动开发系列34 - Linux Graphics Intel 动态显存技术的实现

一:概述 动态显存技术(Dynamic Video Memory Technology, DVMT)是一种由 Intel 提出的内存分配技术,主要用于整合显卡(集成显卡)系统中,以便动态地调整显存大小,从而在不同的负载场景下优化内存使用和系统性能。 动态显存技术的核心在于共享系统内存。集成显卡没有独立…