Code coverage report for src/helpers/visitor.ts

# All files / src/helpers visitor.ts

100% Statements 27/27
100% Branches 7/7
100% Functions 2/2
100% Lines 27/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    281x
    1x
    1x
    1x
    1x
    1x
    1x
    1x
    24x
    24x
    4x
    24x
    20x
    20x
    24x
    24x
    24x
    1x
    81x
    81x
    81x
    81x
    81x
    81x
    22x
    22x
    81x
     /* eslint-disable @typescript-eslint/ban-types */

    type Callback<T = any> = (value: T, key: string, parent: any) => T;

    /**
     * visits all values in a complex object.
     * allows us to perform trasformations on values
     */
    export function visit<T extends object = any>(value: T, callback: Callback): T {
        if (Array.isArray(value)) {
            value.forEach((_, index) => visitKey(index, value, callback));
        } else {
            Object.keys(value).forEach((key) => visitKey(key as keyof T, value, callback));
        }

        return value;
    }

    function visitKey<T extends object, K extends keyof T>(key: K, parent: T, callback: Callback<T[K]>) {
        const keyValue = parent[key];

        parent[key] = callback(keyValue, key as string, parent);

        if (typeof keyValue === 'object') {
            visit(keyValue as any, callback);
        }
    }