For many projects, certain configuration items or query conditions are required. When the user loses the configuration data or the project goes offline, it will cause the project to fail due to errors. At this time, the development needs to provide some bottom-up strategies. For example, the first item is used by default when the current list data cannot be queried.

ensure-get-list-val

It is very troublesome to write these things every time, so here is a package, the code is as follows:

 interface EnsureGetValFromListParams<ItemType, ValueType> {
    /** 列表数据 **/
    items: ItemType[]
    value?: ValueType | undefined
    /** 列表中数据值的提取方法 **/
    getVal?: (item: ItemType) => ValueType
    /** 查询不到数据时候返回值的位置 **/
    pos?: 'frist' | 'last'
}

// ValueType = ItemType
// 如果不提供 ValueType, 则 ValueType 默认为 ItemType
const ensureGetValFromList = <ItemType, ValueType = ItemType>({
    items,
    value,
    getVal = item => item as unknown as ValueType,
    pos = 'frist'
}: EnsureGetValFromListParams<ItemType, ValueType>): ValueType | null => {
    // 当前不是数组直接返回 null
    if (!Array.isArray(items)) {
        return null
    }

    const count = items.length
    // 当前为空数组直接返回 null
    if (count === 0) {
        return null;
    }

    // 没有传递数值或者当前列表长度为1,直接返回列表唯一数据
    if (!value || count === 1) {
        return getVal(items[0])
    }

    // 查询列表,是否有数值等于传入数值
    if (items.some(item => getVal(item) === value)) {
        return value
    }

    // 返回列表第一条还是最后一条数据
    const index = pos === 'frist' ? 0 : count - 1
    return getVal(items[index])
}

The code is in ensure-get-list-val . It can also be installed and used using tools such as npm.

encourage

If you think this article is good, I hope you can give me some encouragement and help to star it under my github blog.

blog address


jump__jump
2.5k 声望4k 粉丝

猎奇者...未来战士...very vegetable