typescript 基于目标函数的动态滤波器构建

irlmq6kh  于 2023-08-07  发布在  TypeScript
关注(0)|答案(1)|浏览(116)

我正在构建一个动态过滤器,类似于Yahoo Screener。以下是我如何为可用字段定义接口:

export interface FilterField {
    label: string;
    selected: boolean;
    deletable: boolean;
    required?: boolean;
    lastValue?: any;
    viewSync?: boolean;
    inclusion?: 'include' | 'exclude';
    precision?: 'before' | 'after' | 'exact';
    controlType?: 'multiselect' | 'time' | 'tag';
    items?: Array<unknown>;
    f?: Function;
}

字符串
这些滤镜的数组如下所示:

public fields: Array<FilterField> = [
        {
            label: 'period',
            viewSync: true,
            selected: true,
            deletable: false,
            lastValue: null,
            required: true,
            f: (data: SomeObject) => {
                // here comes the filtering function
            }
        },
        {
            label: 'dayOfWeek',
            inclusion: 'include',
            selected: true,
            deletable: true,
            lastValue: [1,2],
            f: (data: SomeObject) => {
                // here comes the filtering function
            }
        },
        {
            label: 'startHour',
            precision: 'after',
            selected: true,
            deletable: true,
            lastValue: '12:00',
            controlType: 'time',
            f: (data: SomeObject) => {
                // here comes the filtering function
            }
        }, [...]


当字段被选中时,我需要根据这些字段、它们的lastValue和其他属性(如inclusionprecision)来过滤数据。我的想法是将f: Function设置为回调函数,该回调函数将用于过滤数据。数据本身是一个对象数组,其中一些回调需要包含非常具体的逻辑。
如何定义这样的函数,以及在执行回调时如何读取该特定字段的属性?就像dayOfWeek一样,我需要知道它是应该被包括还是排除,以及哪些日期是由用户设置的。我的脑海中浮现出这样的想法,但这绝对不够:

label: 'dayOfWeek',
            inclusion: 'include',
            selected: true,
            deletable: true,
            lastValue: [1,2],
            f: (data: SomeObject) => {
                return inclusionPropertyOfThisObject == 'include'
                ? lastValuesOfThisParticularObject.includes(moment(data.date).startOf('day').day())
                : !lastValuesOfThisParticularObject.includes(moment(data.date).startOf('day').day())
            }


我该如何实现这个想法?

kuarbcqp

kuarbcqp1#

如果您键入过滤器函数来同时接受数据和过滤器字段,会怎么样?例如:

export interface FilterField<T> {
    label: string;
    selected: boolean;
    deletable: boolean;
    required?: boolean;
    lastValue?: any;
    viewSync?: boolean;
    inclusion?: 'include' | 'exclude';
    precision?: 'before' | 'after' | 'exact';
    controlType?: 'multiselect' | 'time' | 'tag';
    items?: Array<T>;
    f?: (data: T, field: FilterField<T>) => boolean;
}

字符串
您必须对f的调用方式进行一些调整,但这样可以同时访问字段和数据。使用您的示例:

f: (data: SomeObject, field: FilterField<SomeObject>) => {
    return field.inclusion == 'include'
    ? field.lastValues.includes(moment(data.date).startOf('day').day())
    : !field.lastValues.includes(moment(data.date).startOf('day').day())
}

相关问题