Fast deep clone in javascript

function recursiveDeepClone(o) {
    var newO,  i;

    if (typeof o !== 'object') { return o; }
    if (!o) {  return o;  }
    
    if ( Buffer.isBuffer(o) ) {
        let o2 = Buffer.alloc(o.length);
        o.copy(o2);
        return o2;
    }
    
    if ( o.constructor === Int8Array ) {
        newO = new Int8Array( o );
        return newO;
    }
    
    if ( o.constructor === Uint8Array ) {
        newO = new Uint8Array( o );
        return newO;
    }
    
    if ( o.constructor === Uint8ClampedArray ) {
        newO = new Uint8ClampedArray( o );
        return newO;
    }
    
    if ( o.constructor === Int16Array ) {
        newO = new Int16Array( o );
        return newO;
    }
    
    if ( o.constructor === Uint16Array ) {
        newO = new Uint16Array( o );
        return newO;
    }
    
    if ( o.constructor === Int32Array ) {
        newO = new Int32Array( o );
        return newO;
    }
    
    if ( o.constructor === Uint32Array ) {
        newO = new Uint32Array( o );
        return newO;
    }
    
    if ( o.constructor === Float32Array ) {
        newO = new Float32Array( o );
        return newO;
    }
    
    if ( o.constructor === Float64Array ) {
        newO = new Float64Array( o );
        return newO;
    }

    if ( o.constructor === Array ) {
        newO = [];
        for (i = 0; i < o.length; i += 1) {
            newO[i] = recursiveDeepClone(o[i]);
        }
        return newO;
    }
    
    newO = {};
    for (i in o) {
        newO[i] = recursiveDeepClone(o[i]);
    }
    return newO;
}

Reference

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *