動態

詳情 返回 返回

前端開發之函數式編程實踐 | 京東雲技術團隊 - 動態 詳情

作者:京東科技 牛志偉

函數式編程簡介

常見應用場景

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在線報表是一款報表應用工具:易學易用,零代碼,通過簡單拖拽操作,製作中國式複雜報表,輕鬆實現報表的多樣展示、交互分析、數據導出等需求, 在線體驗

已有功能:在線報表中的每個單元格都可以配置相關的屬性:比如擴展方向、父格、單元格格式、過濾條件、條件屬性等

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

大致設計思路

  1. 獲取當前批量設置中,所有的配置項信息
  2. 為每個配置項設計一個處理器(高階函數):主要處理【批量設置的配置信息】和【當前單元格的配置信息】合併或替換邏輯
  3. 通過管道的方式,加工每個單元格所有的配置項信息

核心實現

• 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)));
    //...
}

總結

  1. 函數式編程可以可提高代碼的可重用性,減少重複代碼的開發時間;
  2. 函數式編程可以提高代碼的可讀性,使得代碼更容易理解和調試;
  3. 函數式編程可以更容易實現函數組合,以幫助提高可維護性;
  4. 組合優於繼承;
user avatar segmentfault 頭像 judei 頭像 danshendeyoutiao_zh9e3 頭像 jacklv 頭像 bizidadejianbing 頭像 hole 頭像 shixiansheng_67ea5ae9c45b7 頭像 changqingdezi 頭像 echo_numb 頭像 apocelipes 頭像 kindlingx 頭像 fulng 頭像
點贊 13 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.