blog icon indicating copy to clipboard operation
blog copied to clipboard

30行代码实现深拷贝

Open xianzou opened this issue 4 years ago • 0 comments

const typeList = [
    'string',
    'number',
    'undefined',
    'boolean',
    'function'
];

function isTypeList(obj) {
    if (obj === null) {
        return true;
    }
    const type = typeof obj;

    return typeList.includes(type);
}

function deepCopy(value) {
    if (isTypeList(value)) {
        return value;
    }
    if (Array.isArray(value)) {
        return value.map(item => deepCopy(item));
    }
    if (value instanceof Date) {
        return new Date(value);
    }
    return Object.entries(value).reduce((preData, [key, val]) => {
        preData[key] = deepCopy(val);
        return preData;
    }, {});
}

xianzou avatar Feb 29 '20 09:02 xianzou