作者:京東科技 牛志偉
函式式編程簡介
常見應用場景
1、ES6中的map、filter、reduce等函式
[1,2,3,4,5].map(x => x * 2).filter(x => x > 5).reduce((p,n) => p + n);
2、React類組件 -> 函式式組件+hooks、Vue3中的組合式API
3、RxJS、Lodash和Ramda等JS庫
4、中間件/插件,如Redux中的applyMiddleware中間件實作
const store = applyMiddleware(...middlewares)(createStore)(reducer, initialState)

什么是函式式編程
函式式編程是一種編程范式,它將程式抽象為函式和資料結構,通過函式呼叫來實作程式的功能,并且函式可以作為引數傳遞給其他函式,
在 JavaScript 中,函式式編程可以實作面向物件編程的一些功能,比如抽象、封裝、繼承和多型等,
它還可以使用高階函式、柯里化、組合和延遲計算來實作函式式編程的功能,
函式式編程有哪些特性
函式是「一等公民」
? 函式可以當做引數傳遞給其他函式,也可以作為函式的回傳值回傳(高階函式),
惰性執行
? 惰性執行是指在代碼中的某些函式呼叫,只有在它們的回傳值被使用時才會被執行,
? 它利用了延遲計算的技術,使得函式只在被呼叫時才會執行,而不是在撰寫代碼時就被執行,
? 這樣可以提高性能,因為不需要無用的計算,
無副作用(純函式)
? 函式的執行不會改變程式的外部狀態,也就是說函式的執行不會影響程式的其他部分,
? 因為它只是單純的計算結果,而不會產生其他的副作用,
常見函式式概念
柯里化-currying
柯里化函式是把接受多個引數的函式變換成接受一個單一引數(最初函式的第一個引數)的函式,并且回傳接受余下的引數而且回傳結果的新函式的技術,
函式表達:f(a, b, c) => f(a)(b)(c)
簡單實作(有興趣的同學可以研究下Lodash和Ramda庫中的實作)
// 函式柯里化
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
}
// 自由組合引數
const currySum = curry(sum)
console.log(currySum(1)(2)(3)) //6
console.log(currySum(1)(2,3)) //6
console.log(currySum(1,2)(3)) //6
管道-pipe
管道pipe函式是一個高階函式,它接受一系列函式作為引數,將函式串聯起來,一步步將上一步的輸出作為下一步的輸入,這樣可以更加高效地處理復雜的業務邏輯,
函式表達:pipe(f, g, t) => x => t(g(f(x)),進一步結合curry可以實作pipe(f)(g)(t) => x => t(g(f(x))
借助reduce簡單實作,支持異步和非異步函式
export const pipe: any =
(...fns: Promise<Function>[]) =>
(input: any) =>
fns.reduce((chain: Promise<Function>, func: Function | Promise<Function> | any) => chain.then(func), Promise.resolve(input));
組合-compose
組合compose指的是將多個函陣列合成一個函式,這樣一個函式的輸出就可以作為另一個函式的輸入,從而實作多個函式的鏈式呼叫,
組合compose可以提高代碼的可讀性和可維護性,減少重復代碼的出現,更加便捷的實作函式的復用,
函式表達:compose(f, g, t) => x => f(g(t(x)),進一步結合curry可以實作compose(f)(g)(t) => x => f(g(t(x))
借助reduceRight簡單實作,和pipe的區別只是運算順序不同
export const compose: any =
(...fns: Promise<Function>[]) =>
(input: any) =>
fns.reduceRight((chain: Promise<Function>, func: Function | Promise<Function> | any) => chain.then(func), Promise.resolve(input));
函式式編程實踐
需求背景介紹
AgileBI在線報表是一款報表應用工具:易學易用,零代碼,通過簡單拖拽操作,制作中國式復雜報表,輕松實作報表的多樣展示、互動分析、資料匯出等需求, 在線體驗
已有功能:在線報表中的每個單元格都可以配置相關的屬性:比如擴展方向、父格、單元格格式、過濾條件、條件屬性等

新增需求:需要支持批量設定單元格,其中【文本型別】單元格支持擴展方向、父格的設定;【欄位型別】、【公示型別】單元格支持所有配置;

大致設計思路
-
獲取當前批量設定中,所有的配置項資訊
-
為每個配置項設計一個處理器(高階函式):主要處理【批量設定的配置資訊】和【當前單元格的配置資訊】合并或替換邏輯
-
通過管道的方式,加工每個單元格所有的配置項資訊
核心實作
? pipe函式
private pipe = (...args: any) => {
return (result: any, config?: any) => {
return args.reduce((acc: any, fn: any) => fn(acc, config), result);
};
};
? 高階函式處理每個配置項
// 擴展方向替換
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];
}
//...
? 組合函式,獲取每個單元格的最終配置資訊
//...
let handles: Array<any> = [];
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)));
//...
}
總結
-
函式式編程可以可提高代碼的可重用性,減少重復代碼的開發時間;
-
函式式編程可以提高代碼的可讀性,使得代碼更容易理解和除錯;
-
函式式編程可以更容易實作函陣列合,以幫助提高可維護性;
-
組合優于繼承;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/552542.html
標籤:JavaScript
上一篇:20230515學習筆記——js中的同步任務與異步任務,宏任務與微任務
下一篇:返回列表
