Javascript utils

195 阅读1分钟
/**
 * @desc: 类型检测: 可以检测任意类型的数据
 * @param {*} data
 * @example:
 */
export function typeOf(data) {
  return Object.prototype.toString.call(data).slice(8, -1).toLowerCase();
}

/**
 * @desc: 手机号脱敏 
 * @param {*} mobile
 * @example: 
 * @author: 
 */
export const hideMobile = (mobile) => {
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2")
}

/**
 * @desc: 生成uuid
 * @example: 
 * @author: 
 */
export const uuid = () => {
  const temp_url = URL.createObjectURL(new Blob())
  const uuid = temp_url.toString()
  URL.revokeObjectURL(temp_url) //释放这个url
  return uuid.substring(uuid.lastIndexOf('/') + 1)
}

/**
 * @desc: 全屏
 * @param {*} element
 * @example:
 * @author:
 */
export const launchFullscreen = (element) => {
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullScreen();
  }
};

/**
 * @desc: 关闭全屏
 * @example:
 * @author:
 */
export const exitFullscreen = () => {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  }
};

/**
 * @desc: 树形结构遍历
 * @param {*} data
 * @param {*} callback
 * @param {*} childrenName
 * @example:
 * foreachTree(data, (item) => {
 *    if (item.id === 9) {
 *     result = item
 *    }
 * })
 * @author:
 */
export const foreachTree = (data, callback, childrenName = "children") => {
  for (let i = 0; i < data.length; i++) {
    callback(data[i]);
    if (data[i][childrenName] && data[i][childrenName].length > 0) {
      foreachTree(data[i][childrenName], callback, childrenName);
    }
  }
};

// 防抖
function debounce(callback, wait = 3000, immediate = false) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);

    if (immediate && !timer) {
      callback.apply(this, args);
    }

    timer = setTimeout(() => {
      callback.apply(this, args);
    }, wait);
  };
}

// 节流
function throttle(callback, wait = 1000) {
  let previous = 0;
  let timer = null;

  return function (...args) {
    if (timer) clearTimeout(timer);

    let now = +new Date();

    if (now - previous < wait) {
      timer = setTimeout(() => {
        callback.apply(this, args);
      }, wait);
    } else {
      previous = now;
      callback.apply(this, args);
    }
  };
}

// 执行一次
function once(callback) {
  let called = false;
  return function () {
    if (!called) {
      called = true;
      callback.apply(this, arguments);
    }
  };
}

// 是否为ios平台
function isIos() {
  var u = navigator.userAgent;
  return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
}

/**
 * @desc:
 * @param {*} file: 二进制对象
 * @example:
 */
export function genObjectURL(file) {
  var url = null;
  if (window.createObjectURL != void 0) {
    url = window.createObjectURL(file);
  } else if (window.URL != void 0) {
    url = window.URL.createObjectURL(file);
  } else if (window.webkitURL != void 0) {
    url = window.webkitURL.createObjectURL(file);
  }
  return url;
}

/**
 * @desc: 深拷贝
 * 这个方法有几个问题:
 *  1. 会忽略undefined
 *  2. 会忽略symbol
 *  3. 不能序列化函数
 *  4. 不能解决循环引用的对象
 *  5. 不能处理正则
 *  6. 不能正确处理new Date()
 * @param {*} sourceObj
 * @example:
 */
export function deepClone(sourceObj) {
  return JSON.parse(JSON.stringify(sourceObj));
}

/**
 * @desc: 递归方法实现深度克隆原理:遍历对象、数组直到里边都是基本数据类型,然后再去复制,就是深度拷贝。
 * @param {*} obj
 * @param {*} hash
 * @example: 
 */
export function deepClonePlus(obj, hash = new WeakMap()) {
  if (obj == null) return obj; // 如果是null或者undefined我就不进行拷贝操作
  if (obj instanceof Date) return new Date(obj);
  if (obj instanceof RegExp) return new RegExp(obj);
  // 可能是对象或者普通的值  如果是函数的话是不需要深拷贝
  if (typeof obj !== "object") return obj;
  // 是对象的话就要进行深拷贝
  if (hash.get(obj)) return hash.get(obj);
  // 当obj为 {} 或 [], 使用new obj.constructor()可以处理不同的类型
  let cloneObj = new obj.constructor();
  hash.set(obj, cloneObj);
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      // 实现一个递归拷贝
      cloneObj[key] = deepClonePlus(obj[key], hash);
    }
  }
  return cloneObj;
}

/**
 * @desc: 从url获取参数并转为对象
 * @param {*} URL
 * @example: https://www.google.com.hk/search?q=js+md&newwindow=1
 * @author: 
 */
export function getParameters(URL) {
  return JSON.parse(
    `{"${decodeURI(URL.split("?")[1])
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')}"}`
  );
}