js 工具类

239 阅读1分钟
class myTools {
  constructor(base) {
    this._ = require('lodash');
    this.fileStream = require('fs'); // node模块
    this.base = base;
  }
/** 
 * 深拷贝
 * @param {Object} initalObj
 * @param {Object} finalObj
 */
deepClone(initalObj, finalObj) {
    var obj = finalObj || {};
    for (var i in initalObj) {
    	console.log('i:' + i)
    	var prop = initalObj[i]; // 避免相互引用对象导致死循环,如initalObj.a = initalObj的情况
    	if (prop === obj) {
    		continue;
    	}
    	console.log('prop.constructor:' + prop.constructor)
    	if (typeof prop === 'object') {
    		obj[i] = (prop.constructor === Array) ? [] : Object.create(prop);
    	} else {
    		obj[i] = prop;
    	}
    }
    return obj;
} 
/** 
* 此代码段查找两个数组之间的差异
* difference([1, 2, 3], [1, 2, 4]) // [3]
*/
difference = (a, b) => {
	const s = new Set(b);
	return a.filter(x => !s.has(x));
}
/**
   * 两数组交集
   * @author Machan
   * @date 2019-12-26
   * @param {Array} arr1
   * @param {Array} arr2
   * @returns {Array}
   */
  arrayIntersection(arr1, arr2) {
    const theSet = new Set(arr2);
    return arr1.filter(x => theSet.has(x));
  }
  /**
   * 数组去重终极方案
   * @author Machan
   * @date 2019-12-28
   * @param {Array} arr
   * @returns {Array}
   */
 function unique(arr) {
    var obj = {};
    return arr.filter(function(item, index, arr){
        return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)
    })
} 
/**
   * 按对象属性排序 max to min
   * @author Machan
   * @date 2019-12-17
   * @params {a: 10, b:5, c:20}
   * @returns {Object} 同原数据 只排序
   */
  getSortWuxingScore(obj) {
    let resultObj = {};
    let wuxingObj = obj;
    let keysSort = Object.keys(wuxingObj).sort(function(a, b) {
      return wuxingObj[b] - wuxingObj[a];
    });
    keysSort.forEach(key => {
      resultObj[key] = wuxingObj[key];
    });
    return resultObj;
  }
}
module.exports = myTools;