Sobes.tech
Junior — Senior

Analysis of the data table filtering function

livecode

Task condition

This task requires understanding how the provided code snippet works.

 import { copyObj } from "core/iterable_utils";

export const useSomDbFilterTableData = (tableData) => {
    const filterTableData = (searchValue) => {
        const newTableData = copyObj(tableData).map((row) => {
            const filterRow = (row) => {
                row.visible = true;
                if (row.model_name === "SonItem") {
                    if (
                        !String(row.code).toLowerCase().includes(searchValue.toLowerCase()) &&
                        !String(row.name).toLowerCase().includes(searchValue.toLowerCase())
                    ) {
                        row.visible = false;
                    }
                } else if ("_children" in row) {
                    const children = row._children;
                    children.forEach((childRow) => {
                        filterRow(childRow);
                    });
                    if (!children.some((childRow) => childRow.visible)) {
                        row.visible = false;
                    }
                }
            };
            filterRow(row);
            return row;
        });

        return newTableData;
    };
};

The code exports a function useSomDbFilterTableData that takes an initial array tableData. Inside, a helper function filterRow is defined, which recursively traverses each element and its descendants (if it has the _children property). For rows of type SonItem, it checks whether the fields code or name contain the substring searchValue (case-insensitive). If neither field contains the search string, the visible property of the row is set to false. For nodes with children, the function first processes all children, and if none of the children are marked as visible, it also hides the parent node. After processing all rows, a new array newTableData with updated visible flags is returned.