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,一经查实,立即删除!

相关文章

【大模型知识点】什么是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】通过…

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

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

LSTM变种模型

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

微服务与网关

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

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

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

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

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

实现:多活的基础中间件

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

DeepSeek本地化部署

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

大数据与大模型:数字时代的共生力量

引言:大数据与大模型的崭新时代 在数字化浪潮汹涌澎湃的当下,大数据与大模型无疑是最为耀眼的两颗明星 ,深刻地改变着我们的生活、工作和思维方式。大数据,作为信息时代的宝藏,蕴含着无尽的价值。从电商平台的海量交易…

[2025年最新]2024.3版本idea无法安装插件问题解决

背景 随着大模型的持续发展,特别年前年后deepseek的优异表现,编程过程中,需要解决ai来辅助编程,因此需要安装一些大模型插件 问题描述 在线安装插件的时候会遇到以下问题: 1.数据一直在加载,加载的很满 2.点…

自动驾驶---如何打造一款属于自己的自动驾驶系统

在笔者的专栏《自动驾驶Planning决策规划》中,主要讲解了行车的相关知识,从Routing,到Behavior Planning,再到Motion Planning,以及最后的Control,笔者都做了相关介绍,其中主要包括算法在量产上…

三角拓扑聚合优化器TTAO-Transformer-BiLSTM多变量回归预测(Maltab)

三角拓扑聚合优化器TTAO-Transformer-BiLSTM多变量回归预测(Maltab) 完整代码私信回复三角拓扑聚合优化器TTAO-Transformer-BiLSTM多变量回归预测(Maltab) 一、引言 1、研究背景和意义 在现代数据科学领域,时间序列…

Jenkins+gitee 搭建自动化部署

Jenkinsgitee 搭建自动化部署 环境说明: 软件版本备注CentOS8.5.2111JDK1.8.0_211Maven3.8.8git2.27.0Jenkins2.319最好选稳定版本,不然安装插件有点麻烦 一、安装Jenkins程序 1、到官网下载相应的版本war或者直接使用yum安装 Jenkins官网下载 直接…

AI 编程开发插件codeium Windsurf(vscode、editor) 安装

1、vscode中安装: 2、vscode中使用 3、输入注册的账号密码,就可以使用。 4、或者直接下载editor 5、安装editor 下一步,下一步,直到安装成功,中间可以改下安装位置,如果C盘空间不够。 同样提示注册或者登录…

【Mac排错】ls: command not found 终端命令失效的解决办法

【TroubleShooting on Mac】ls: command not found 终端命令失效的解决办法 A Solution to Solve “Command not found” of Terminal on Mac 一直在使用心爱的MacBook Pro的Terminal,并且为她定制了不同的Profile。 这样,看起来她可以在不同季节&…

河北某石油管廊自动化监测

1. 项目简介 近年来,国家密集出台油气管道建设相关政策和规划引导中国油气管道加快建设,2017年,在《中长期油气管网规划》中对2025年和2030年油气管道发展目标均作出了相应的规划目标。另一方面,随着油气管道行业的发展&#xff…

问题:通过策略模式+工厂模式+模板方法模式实现ifelse优化

项目场景: 提示:这里简述项目相关背景: 示例:商城系统有会员系统,不同会员有不同优惠程度,普通会员不优惠;黄金会员打8折;白金会员优惠50元,再打7折; 问题描…

Android ndk兼容 64bit so报错

1、报错logcat如下 2025-01-13 11:34:41.963 4687-4687 DEBUG pid-4687 A #01 pc 00000000000063b8 /system/lib64/liblog.so (__android_log_default_aborter16) (BuildId: 467c2038cdfa767245f9280e657fdb85) 2025…

centos安装Nexus Repository OSS(Maven私服)

1. 下载链接:https://help.sonatype.com/en/download.html 2. 注意页面下载页面中的要求:JDK17(启动时提示最低JDK1.8最高JDK17,但是使用JDK1.8无法正常启动) 3. mkdir /opt/nexus 将压缩包上传到该目录并解压。 tar …