![](http://img.inpai.com.cn/2023/0410/20230410091623448.jpg)
一、函數(shù)式編程簡(jiǎn)介
常見(jiàn)應(yīng)用場(chǎng)景
【資料圖】
1、ES6中的map、filter、reduce等函數(shù)
[1,2,3,4,5].map(x => x * 2).filter(x => x > 5).reduce((p,n) => p + n);2、React類組件 -> 函數(shù)式組件+hooks、Vue3中的組合式API3、RxJS、Lodash和Ramda等JS庫(kù) 4、中間件/插件,如Redux中的applyMiddleware中間件實(shí)現(xiàn)
const store = applyMiddleware(...middlewares)(createStore)(reducer, initialState)??什么是函數(shù)式編程函數(shù)式編程是一種編程范式,它將程序抽象為函數(shù)和數(shù)據(jù)結(jié)構(gòu),通過(guò)函數(shù)調(diào)用來(lái)實(shí)現(xiàn)程序的功能,并且函數(shù)可以作為參數(shù)傳遞給其他函數(shù)。 在 JavaScript 中,函數(shù)式編程可以實(shí)現(xiàn)面向?qū)ο缶幊痰囊恍┕δ埽热绯橄?、封裝、繼承和多態(tài)等。 它還可以使用高階函數(shù)、柯里化、組合和延遲計(jì)算來(lái)實(shí)現(xiàn)函數(shù)式編程的功能。
函數(shù)式編程有哪些特性
函數(shù)是「一等公民」
函數(shù)可以當(dāng)做參數(shù)傳遞給其他函數(shù),也可以作為函數(shù)的返回值返回(高階函數(shù))。
惰性執(zhí)行
惰性執(zhí)行是指在代碼中的某些函數(shù)調(diào)用,只有在它們的返回值被使用時(shí)才會(huì)被執(zhí)行。
它利用了延遲計(jì)算的技術(shù),使得函數(shù)只在被調(diào)用時(shí)才會(huì)執(zhí)行,而不是在編寫(xiě)代碼時(shí)就被執(zhí)行。
這樣可以提高性能,因?yàn)椴恍枰獰o(wú)用的計(jì)算。
無(wú)副作用(純函數(shù))
函數(shù)的執(zhí)行不會(huì)改變程序的外部狀態(tài),也就是說(shuō)函數(shù)的執(zhí)行不會(huì)影響程序的其他部分。
因?yàn)樗皇菃渭兊挠?jì)算結(jié)果,而不會(huì)產(chǎn)生其他的副作用。
二、常見(jiàn)函數(shù)式概念
柯里化-currying
柯里化函數(shù)是把接受多個(gè)參數(shù)的函數(shù)變換成接受一個(gè)單一參數(shù)(最初函數(shù)的第一個(gè)參數(shù))的函數(shù),并且返回接受余下的參數(shù)而且返回結(jié)果的新函數(shù)的技術(shù)。 函數(shù)表達(dá):f(a, b, c) => f(a)(b)(c) 簡(jiǎn)單實(shí)現(xiàn)(有興趣的同學(xué)可以研究下Lodash和Ramda庫(kù)中的實(shí)現(xiàn))
// 函數(shù)柯里化function curry(fn, args){ args = args || [] return function(...params){ let _args = [...args, ...params] if(_args.length < fn.length){ return curry(fn, _args) } return fn.apply(this, _args) }}function sum(a, b, c){ return a+b+c}// 自由組合參數(shù)const currySum = curry(sum)console.log(currySum(1)(2)(3)) //6console.log(currySum(1)(2,3)) //6console.log(currySum(1,2)(3)) //6
管道-pipe
管道pipe函數(shù)是一個(gè)高階函數(shù),它接受一系列函數(shù)作為參數(shù),將函數(shù)串聯(lián)起來(lái),一步步將上一步的輸出作為下一步的輸入,這樣可以更加高效地處理復(fù)雜的業(yè)務(wù)邏輯。 函數(shù)表達(dá):pipe(f, g, t) => x => t(g(f(x)),進(jìn)一步結(jié)合curry可以實(shí)現(xiàn)pipe(f)(g)(t) => x => t(g(f(x)) 借助reduce簡(jiǎn)單實(shí)現(xiàn),支持異步和非異步函數(shù)
export const pipe: any = (...fns: Promise[]) => (input: any) => fns.reduce((chain: Promise , func: Function | Promise | any) => chain.then(func), Promise.resolve(input));
組合-compose
組合compose指的是將多個(gè)函數(shù)組合成一個(gè)函數(shù),這樣一個(gè)函數(shù)的輸出就可以作為另一個(gè)函數(shù)的輸入,從而實(shí)現(xiàn)多個(gè)函數(shù)的鏈?zhǔn)秸{(diào)用。 組合compose可以提高代碼的可讀性和可維護(hù)性,減少重復(fù)代碼的出現(xiàn),更加便捷地實(shí)現(xiàn)函數(shù)的復(fù)用。 函數(shù)表達(dá):compose(f, g, t) => x => f(g(t(x)),進(jìn)一步結(jié)合curry可以實(shí)現(xiàn)compose(f)(g)(t) => x => f(g(t(x)) 借助reduceRight簡(jiǎn)單實(shí)現(xiàn),和pipe的區(qū)別只是運(yùn)算順序不同
export const compose: any = (...fns: Promise三、函數(shù)式編程實(shí)踐[]) => (input: any) => fns.reduceRight((chain: Promise , func: Function | Promise | any) => chain.then(func), Promise.resolve(input));
需求背景介紹
AgileBI在線報(bào)表是一款報(bào)表應(yīng)用工具:易學(xué)易用,零代碼,通過(guò)簡(jiǎn)單拖拽操作,制作中國(guó)式復(fù)雜報(bào)表,輕松實(shí)現(xiàn)報(bào)表的多樣展示、交互分析、數(shù)據(jù)導(dǎo)出等需求, 在線體驗(yàn) 已有功能:在線報(bào)表中的每個(gè)單元格都可以配置相關(guān)的屬性:比如擴(kuò)展方向、父格、單元格格式、過(guò)濾條件、條件屬性等 ??新增需求:需要支持批量設(shè)置單元格,其中【文本類型】單元格支持?jǐn)U展方向、父格的設(shè)置;【字段類型】、【公示類型】單元格支持所有配置;??大致設(shè)計(jì)思路
獲取當(dāng)前批量設(shè)置中,所有的配置項(xiàng)信息
為每個(gè)配置項(xiàng)設(shè)計(jì)一個(gè)處理器(高階函數(shù)):主要處理【批量設(shè)置的配置信息】和【當(dāng)前單元格的配置信息】合并或替換邏輯
通過(guò)管道的方式,加工每個(gè)單元格所有的配置項(xiàng)信息
核心實(shí)現(xiàn)
?pipe函數(shù)
private pipe = (...args: any) => { return (result: any, config?: any) => { return args.reduce((acc: any, fn: any) => fn(acc, config), result); };};?高階函數(shù)處理每個(gè)配置項(xiàng)
// 擴(kuò)展方向替換private handleExpand(expandConf: string) { return (conf: any) => { if (expandConf) { conf.expandDirection = expandConf; } return conf; };}// 父行/父列替換private handleParentCell(columnParentCell: any, rowParentCell: any) { return (conf: any) => { if (columnParentCell?.parentSelectType) { conf.columnParentCell = columnParentCell; } if (rowParentCell?.parentSelectType) { conf.rowParentCell = rowParentCell; } return conf; };}// 條件屬性追加private handleCondition(conditionBatchConf: any) { return (conf: any) => { conf.conditionConf = this.mergeCondition(conf?.conditionConf || [], conditionBatchConf); return conf; };}// 批量修改private mergeCondition(c1: any, c2: any) { for (let j = 0; j < c1.length; j++) { // 批量刪除 if ( c1[j]?.batchFlag && this.batchConf.conditionConf?.find((item: any) => item.uuid === c1[j]?.uuid) && !c2.find((item: any) => item.uuid === c1[j]?.uuid) ) { c1.splice(j, 1); } } for (let j = 0; j < c1.length; j++) { for (let i = 0; i < c2.length; i++) { // 如果字段已存在則替換 if (c2[i]?.uuid === c1[j]?.uuid) { c1.splice(j, 1); } } } return [...c1, ...c2];}//...?組合函數(shù),獲取每個(gè)單元格的最終配置信息
//...let handles: Array = [];if (cell?.dataConf?.cellType === "文本") { handles = [ this.handleExpand(conf.expandDirection), this.handleParentCell(conf.columnParentCell, conf.rowParentCell) ];} else if (cell?.dataConf?.cellType === "字段" || cell?.dataConf?.cellType === "公式") { handles = [ this.handleExpand(conf.expandDirection), this.handleParentCell(conf.columnParentCell, conf.rowParentCell), this.handleFormat(conf.dataFormatConf), this.handleFilter(conf.cellFilterConf), this.handleCondition(conf.conditionConf) ];}if (handles.length > 0) { const mergeConf = this.pipe(...handles)(JSON.parse(JSON.stringify(cell.dataConf))); //...}四、總結(jié)
函數(shù)式編程可以可提高代碼的可重用性,減少重復(fù)代碼的開(kāi)發(fā)時(shí)間;
函數(shù)式編程可以提高代碼的可讀性,使得代碼更容易理解和調(diào)試;
函數(shù)式編程可以更容易實(shí)現(xiàn)函數(shù)組合,以幫助提高可維護(hù)性;
組合優(yōu)于繼承;
審核編輯:湯梓紅標(biāo)簽: