关于javascript:确保从列表中获取可用值

9次阅读

共计 1037 个字符,预计需要花费 3 分钟才能阅读完成。

对于很多我的项目来说,某些配置项或查问条件是必须的。当用户失落配置数据或我的项目下线配置项,都会导致我的项目产生谬误而造成不可用的问题,这时候,开发须要提供一些兜底策略,如以后列表数据查问不到时默认应用第一项。

ensure-get-list-val

这些货色每次都写一下又很麻烦,所以这里进行了一次封装,代码如下:

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

代码在 ensure-get-list-val 中。也能够应用 npm 等工具进行装置和应用。

激励一下

如果你感觉这篇文章不错,心愿能够给与我一些激励,在我的 github 博客下帮忙 star 一下。

博客地址

正文完
 0