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

Javascript file path format extraction

輸入一組路徑,轉換成 sprintf  format

如把

'D:\\\\workspace\\path-parser\\img\\img_0005.txt'

轉換為

D:\\\\workspace\\path-parser\\img\\img_%04d.txt

基本上就是個掃目錄的蠢方法,反正成功了…演算法如下,後面附上 Javascript code

  1. 把輸入路徑轉換成 regex (這邊假定是索引最後一組數字字串)
  2. 在對應目錄下用 regex 找符合的檔名,紀錄最長和最短檔名長度
  3. 如果長度相同,就是有 zero padding ( e.g. %04d ),反之沒有
  4. 根據有沒有 zero padding 決定 format 要怎寫

閱讀全文〈Javascript file path format extraction〉