banner
SlhwSR

SlhwSR

热爱技术的一名全栈开发者
github
bilibili

Various implementations of deep copy

Directly enter the code:

/**
 * The problem with JSON.parse(JSON.stringify(object)) is that
 *  1. It ignores undefined
 *  2. It ignores Symbols
 *  3. It cannot serialize functions
 *  4. It cannot solve circular reference objects
 * DeepClone1 -> solves the issue with types, including arrays
 * @param target
 */
export function DeepClone1(target) {
    if (typeof target === 'object') {
        // Consider whether it is an array
        let cloneTarget = Array.isArray(target) ? [] : {};
        for (const key in target) {
            // Do not consider prototype properties
            if (target.hasOwnProperty(key)) {
                // Recursive copy
                cloneTarget[key] = DeepClone1(target[key]);
            }
        }
        return cloneTarget;
        // Non-reference types, return directly
    } else {
        return target;
    }
}

/**
 * Solves the problem of circular references, uses weakMap instead of map for memory release
 * Uses map to allocate additional memory space to store the relationship between the current object and the copied object
 */
export function DeepClone2(target, map = new Map()) {
    if (typeof target === 'object') {
        let cloneTarget = Array.isArray(target) ? [] : {};
        if (map.get(target)) {
            return map.get(target);
        }
        map.set(target, cloneTarget);
        for (const key in target) {
            if (target.hasOwnProperty(key)) {
                cloneTarget[key] = DeepClone2(target[key], map);
            }
        }
        return cloneTarget;
    } else {
        return target;
    }
}

// In addition to objects and functions, reference types also include null and function, which can be encapsulated in an isObject function
function isObject(target) {
    const type = typeof target;
    return target !== null && (type === 'object' || type === 'function');
}

/**
 * Classify data types based on whether they are iterable
 * Iterable: object/array/map/set
 * Not iterable: string/number/boolean/symbol, undefined/null, function, regex/date/error/math/JSON
 * Returns [object Array]
 */
function getType(target) {
    return Object.prototype.toString.call(target);
}

// Function types are returned directly and are generally not considered
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.