簡體   English   中英

是否有 lodash.chain function 的替代品?

[英]Is there an alternative to lodash .chain function?

如果沒有 lodash 鏈 function,我該如何實現?

const results = chain(sortedItems || allItems)
            .filter((x) => this.filterItemsBySearchParam<T>(x, search))
            .filter((x) => this.filterItemsByFacets<T>(x, facets))
            .groupBy((x) => (groupBy ? [groupBy.split(',').map((path) => get(x, path))] : ''))
            .map((filteredItems: any, key) => {
                if (!isNaN(Number(limit))) {
                    filteredItems = [...filteredItems.slice(0, limit)];
                }

                return this.addData<T>(key, filteredItems.length, filteredItems);
            })
            .value();

我嘗試過使用 lodash flow 和其他一些 ES6 函數,但它們都沒有按預期工作。 可能是我沒有正確應用它們?

我試過這個:

const result = sortedItems || allItems
        .filter((x) => this.filterItemsBySearchParam<T>(x, search))
        .filter((x) => this.filterItemsByFacets<T>(x, facets))
        .groupBy((x) => (groupBy ? [groupBy.split(',').map((path) => get(x, path))] : ''))
        .map((filteredItems: any, key) => {
            if (!isNaN(Number(limit))) {
                filteredItems = [...filteredItems.slice(0, limit)];
            }

            return this.addData<T>(key, filteredItems.length, filteredItems);
        });

但是 groupBy 不斷拋出錯誤: groupBy 不是 T 的類型。

我從這里嘗試了 flow: Better and more performance than lodash chain ,但就像我說的,我無法讓它工作。 有沒有辦法做到這一點? 對了,.filter、.map、.groupBy都是內置的ts函數。

嘗試這個:

const filteredItems = (sortedItems || allItems || []).filter(x => this.filterItemsBySearchParam<T>(x, search) && this.filterItemsByFacets<T>(x, facets));
const results = Object.entries(groupBy ? filteredItems.reduce((map, x) => {
    const key = JSON.stringify((groupBy.match(/[^,]+/g) || []).map(path => get(x, path)));
    (map[key] || (map[key] = [])).push(x);
    return map;
}, {}) : {'': filteredItems}).map(([key, filteredItems]) => {
    if (+limit > 0) {
        filteredItems = filteredItems.slice(0, limit);
    }

    return this.addData<T>(key, filteredItems.length, filteredItems);
});

問你是否有任何問題:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM