编码题记录

254 阅读1分钟

查找重复数字

实现一个方法 getSameNumbers,找出同时存在于数组里的所有数字

  • 需要考虑异常情况(参数为空、参数不为数组)

  • 当遇到嵌套数组时,需要在内部数组里找出匹配的数字

  • 返回结果时,相同的数字只出现一次

function getSameNumbers(arr1, arr2) { 
    if(!Array.isArray(arr1) || !Array.isArray(arr1) || (arr1.length === 0) || (arr2.length === 0) ) return '参数异常';
    let newArr = [];
    let newArr1 = [...new Set([].concat.apply([], arr1))];
    let newArr2 = [...new Set([].concat.apply([], arr2))];
    newArr1.forEach(elem => { if(newArr2.includes(elem)) { newArr.push(elem) } })
    return newArr;
}
// getSameNumbers([1, 5, 6], [[1], 1, 2, '6', 7]) 
// 得到 [1]

比较版本大小

Semantic Versioning 是一个前端通用的版本定义规范。格式为“{m}.{n}.{p}-{a|b|c}.{number}”,要求实现 compare(a, b) 方法,比较 a, b 两个版本大小。

  • 当 a > b 是返回 1;

  • 当 a = b 是返回 0;

  • 当 a < b 是返回 -1;

  • 其中,c > b > a,m > n > p;

  • 例子,1.2.3 < 1.2.4 < 1.3.0.a.1 < 1.3.0.a.2 < 1.3.0.b.1 < 1.3.0.c.1 < 1.3.0

function compare(a, b) { 
    if(a === b) return 0;
    const rba = { c: 2, b: 1, a: 0, }
    const arrA = a.split('.');
    const arrB = b.split('.');
    arrA.forEach((elem, index) => { if(elem in rba) { arrA.splice(index,1, rba[elem])}}) 
    arrB.forEach((elem, index) => { if(elem in rba) { arrB.splice(index,1, rba[elem]) } }) 
    let length = Math.min(arrA.length, arrB.length);
    for(var i = 0; i< length; i++) { 
       if(arrA[i] < arrB[i]) { 
           return -1; 
       } else if(arrA[i] > arrB[i]) { 
           return 1; 
       }
    }
    if(length === arrA.length) { 
       return 1; 
    } else { 
       return -1; 
    }
}

对象扁平化

参考文章 t.csdn.cn/5Kr2k

function flatten(obj) { 
    let data = {}; 
    function fft(o, value) { 
        for(let key in o) { 
            if(typeof o[key] === 'object'){ 
                if(!value) { 
                    fft(o[key], key); 
                } else { 
                    if (Array.isArray(o)){ 
                        fft(o[key], value + '[' + key +']'); 
                    } else { 
                        fft(o[key], value + '.' + key); 
                    } 
                }
            } else { 
                if(!value) { 
                    data[key] = o[key] 
                } else { 
                    if (Array.isArray(o)){ 
                        data[value + '[' + key +']'] = o[key];
                    } else { 
                        data[value + '.' + key] = o[key];
                    }
                } 
            }
         }
    }
    
  fft(obj, null);
  
  return data;
}