工具函数2:递归

212 阅读1分钟

1.代码实现

function recursive<T>(
arr: T[], //递归对象
childKey: keyof T, //递归键
fn: //递归函数
    (e: T,//对象
    group: T[], //当前对象所属群组
    level?: number, //层级
    indexInParent?: number, //当前对象在父群组中的下标
    path?: T[]) => void | never, //路径
level?: number, //层级
basePath?: T[]//基础路径
    ) {
    if (level !== undefined) level++
    arr.forEach((_: T, index: number) => {
        const path = []
        if (basePath !== undefined) {
            path.push(...basePath, _)
        }
        fn(_, arr, level, index, path);
        const e = <T[]><unknown>_[childKey];
        if (!e || !Array.isArray(e)) return
        recursive<T>(e, childKey, fn, level, path);
    });
}


2.代码示例

interface Data {
    id: number,
    children?: Data[]
}
const data: Data[] = [
    { id: 1, children: [{ id: 11, children: [] },{ id: 12, children: [] }] },
    { id: 2, children: [{ id: 21, children: [] },{ id: 22, }] },
    { id: 3, children: [{ id: 31, children: [{id:311}] },{ id: 32, children: [{id:321}] }] },
    { id: 4, children: [{ id: 41, children: [] },{ id: 42, children: [] }] },
]

recursive(data, 'children', (e, group, level, indexInParent, path) => {
    console.log(e.id, group.map(_=>_.id), level, indexInParent, path?.map(_=>_.id));
}, 0, [])

/**输出:
    [LOG]: 1,  [1, 2, 3, 4],  1,  0,  [1] 
    [LOG]: 11,  [11, 12],  2,  0,  [1, 11] 
    [LOG]: 12,  [11, 12],  2,  1,  [1, 12] 
    [LOG]: 2,  [1, 2, 3, 4],  1,  1,  [2] 
    [LOG]: 21,  [21, 22],  2,  0,  [2, 21] 
    [LOG]: 22,  [21, 22],  2,  1,  [2, 22] 
    [LOG]: 3,  [1, 2, 3, 4],  1,  2,  [3] 
    [LOG]: 31,  [31, 32],  2,  0,  [3, 31] 
    [LOG]: 311,  [311],  3,  0,  [3, 31, 311] 
    [LOG]: 32,  [31, 32],  2,  1,  [3, 32] 
    [LOG]: 321,  [321],  3,  0,  [3, 32, 321] 
    [LOG]: 4,  [1, 2, 3, 4],  1,  3,  [4] 
    [LOG]: 41,  [41, 42],  2,  0,  [4, 41] 
    [LOG]: 42,  [41, 42],  2,  1,  [4, 42] 
*/

image.png