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.pswp.cn/news/895340.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/895340.shtml
英文地址,請注明出處:http://en.pswp.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 提出的內存分配技術,主要用于整合顯卡(集成顯卡)系統中,以便動態地調整顯存大小,從而在不同的負載場景下優化內存使用和系統性能。 動態顯存技術的核心在于共享系統內存。集成顯卡沒有獨立…