All files clone.js

100% Statements 34/34
100% Branches 17/17
100% Functions 3/3
100% Lines 32/32

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 53 54 551x 1x 1x 1x     37x 37x         37x     16x 16x 2x       14x 4x 13x 1x 12x 1x 1x 2x   1x 11x 1x 1x 5x   1x   10x 10x 24x     10x 10x 1x 1x     10x          
const tagMap = '[object Map]'
const tagSet = '[object Set]'
const tagRegExp = '[object RegExp]'
const tagDate = '[object Date]'
 
function isObj(input) {
    const type = typeof input
    return input !== null && (type === 'object' || type === 'function')
}
 
function clone(val) {
    // 1类 基本数据类型  string, number, boolean, null, undefined, symbol
    if (!isObj(val)) return val
 
    // 2类 Date, RegExp
    const type = Object.prototype.toString.call(val)
    if ([tagDate, tagRegExp].includes(type)) {
        return new val.constructor(val)
    }
 
    // 3类 引用数据类型
    if (Array.isArray(val)) {
        return val.map(v => clone(v))
    } else if (typeof val === 'function') {
        return val
    } else if (type === tagMap) {
        const _map = new Map()
        for (const item of val) {
            _map.set(item[0], clone(item[1]))
        }
        return _map
    } else if (type === tagSet) {
        const _set = new Set()
        for (const item of val) {
            _set.add(clone(item))
        }
        return _set
    } else {
        const _obj = Object.create(Object.getPrototypeOf(val))
        for (const key in val) {
            _obj[key] = clone(val[key])
        }
        // 处理使用Symbols作为属性的项目
        const _sybKeys = Object.getOwnPropertySymbols(val)
        if (_sybKeys.length > 0) {
            for (const key of _sybKeys) {
                _obj[key] = clone(val[key])
            }
        }
        return _obj
    }
}
 
 
export default clone