'Is there an alternative to lodash .chain function?

How do I achieve this without lodash chain 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();

I have tried using lodash flow, and some other ES6 functions, but none of them worked as expected. it could be that I'm not applying them correctly?

I have tried this:

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);
        });

But the groupBy keeps throwing an error: groupBy is not a type of T.

I tried flow from here: Better and more performant than lodash chain, but like I said, I could not get it to work. Is there a way to achieve this? By the way, the .filter, .map, and .groupBy are all built-in ts functions.



Solution 1:[1]

Try this:

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);
});

ask if you have any questions :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vamp