如何使用Ts泛型写一个通用的遍历数组和对象的方法

使用Ts编写一个遍历数组和对象的方法

type Obj<T = any> = { [key in string | number]: T }

type Keys<T> = T extends (infer U)[] ? U : T[Extract<keyof T, string>]

type Callback<T extends Obj> = (item: T extends (infer U)[] ? U : T[Extract<keyof T, string>], index: number, source?: T) => any

type AsyncCallback<T extends Obj> = (item: T extends (infer U)[] ? U : T[Extract<keyof T, string>], index: number, source?: T) => Promise<any>

const isArray = (type: unknown): type is Array<any> => type instanceof Array

const isObject = (type: unknown): type is Obj => typeof type === 'object'

/**
 * 同步遍历当前元素
 * @param source 需要遍历的元素
 * @param fn 遍历的同步回调 返回 true 可以停止遍历
 */
export const each = <T extends Obj> (source: T, fn: Callback<T>): void => {
    if (isArray(source)) {
        for (let i = 0, length = source.length; i < length; i++) {
            if (fn(source[i], i, source) === true) return
        }
    } else if (isObject(source)) {
        const keys = Reflect.ownKeys(source) as Array<keyof T>
        for (let i = 0, length = keys.length; i < length; i++) {
            const key = keys[i]
            if (Reflect.has(source, key) && key !== 'constructor') {
                if (fn(source[key], i, source) === true) return
            }
        }
    } else {
        fn(source, -1)
    }
}

/**
 * 倒序遍历
 * @param source 需要遍历的元素
 * @param fn 遍历的同步回调 返回 true 可以停止遍历
 */
export const reverseEach = <T extends Obj> (source: T, fn: Callback<T>): void => {
    if (isArray(source)) {
        for (let i = source.length - 1; i >= 0; i--) {
            if (fn(source[i], i, source) === true) return
        }
    } else if (isObject(source)) {
        const keys = Reflect.ownKeys(source) as Array<keyof T>
        for (let i = keys.length - 1; i >= 0; i--) {
            const key = keys[i]
            if (Reflect.has(source, key) && key !== 'constructor') {
                if (fn(source[key], i, source) === true) return
            }
        }
    } else {
        fn(source, -1)
    }
}

/**
 * 异步遍历当前元素
 * @param source 需要遍历的元素
 * @param fn 遍历的异步回调 返回 true 可以停止遍历
 */
export const asyncEach = async <T extends Obj> (source: T, fn: AsyncCallback<T>): Promise<void> => {
    if (isArray(source)) {
        for (let i = 0; i < source.length; i++) {
            const result = await fn(source[i], i, source)
            if (result === true) return
        }
    } else if (isObject(source)) {
        const keys = Reflect.ownKeys(source) as Array<keyof T>
        for (let i = 0, length = keys.length; i < length; i++) {
            const key = keys[i]
            if (Reflect.has(source, key) && key !== 'constructor') {
                const result = await fn(source[key], i, source)
                if (result === true) return
            }
        }
    } else {
        await fn(source, -1)
    }
}

使用

const list = [1, 2, 3]
each(list, (item, index) => {
    if (item === 2) {
        console.log(index)
        return true
    }
    console.log('111')
})

const obj: { a: number, b: string, c: { d: number } } = { a: 12, b: '123', c: { d: 1234 } }

each(obj, (item, index) => {
    if (typeof item === 'object') {
        console.log(index, item.d)
        return true
    }
    console.log('222')
})

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值