All files / src/PerfectWSAdvanced/transform/utils changeType.ts

100% Statements 39/39
100% Branches 22/22
100% Functions 4/4
100% Lines 39/39

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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 532x 14487x 14487x 14487x 53435x 1862x 1862x 53435x 14487x 14487x                 2x 26441x 4434x 4434x   22007x 22007x 22007x   26356x 113246x 113246x   113246x 113246x 3725x 3725x 3725x   113246x 10x 10x   113246x 113246x 5158495x 5158495x 5067256x 5067256x 91239x 91239x 109510x   22006x 22006x
export function transformSendDeserializeType(data: any, typeName: string, transformData: (data: any) => any, maxDepth: number = 100) {
    return transformSendRecursive(data, {
        maxDepth,
        transformData: (obj) => {
            if (obj.___type === typeName) {
                return transformData(obj);
            }
        }
    });
}
 
type TransformSendRecursiveOptions = {
    maxDepth?: number;
    transformData: (data: any) => any | null;
    processingDataType?: (data: any) => boolean;
};
 
 
export function transformSendRecursive(obj: any, { transformData, maxDepth = 100, processingDataType = (data: any) => typeof data === 'object' && data !== null }: TransformSendRecursiveOptions) {
    if (!processingDataType(obj)) {
        return obj;
    }
 
    const processed = new WeakSet();
    const parent = { root: obj };
    const stack: { obj: any; depth: number; parent: any, key: string | number; }[] = [{ obj, depth: 0, parent, key: 'root' }];
 
    while (stack.length > 0) {
        const { obj: current, depth, parent, key } = stack.pop()!;
        processed.add(current);
 
        const foundTransform = transformData(current);
        if (foundTransform != null) {
            parent[key] = foundTransform;
            continue;
        }
 
        if (depth >= maxDepth) {
            continue;
        }
 
        const currentKeys = Array.isArray(current) ? current.keys() : Object.keys(current);
        for (const key of currentKeys) {
            const value = current[key];
            if (!processingDataType(value) || processed.has(value)) {
                continue;
            }
            stack.push({ obj: value, depth: depth + 1, key, parent: current });
        }
    }
 
    return parent.root;
}