pc端常用方法

525
  • 深度比较2个对象是否不同
  • 获取链接中参数列表
  • 逗号拼接参数
  • 格式化筛选参数
  • 数组对象深度克隆复制
  • 电子邮件验证
  • 手机号码验证
  • base64解码、编码
  • js数据类型的判断
  • 数组去重返回新数组
  • 函数防抖
  • 原生设置cookie
  • 函数柯里化
  • 控制时间
  • 删除对象的指定属性
  1. 深度比较2个对象是否不同
import { transform, isEqual, isObject } from "lodash";
/**
 * 使用 lodash 深度比较2个对象是否不同
 * @param  {Object} object 比较来源
 * @param  {Object} base  比较目标
 * @return {Object} 返回一个包含2个比较对象中不同属性的对象
 */
export function difference(object, base) {
  return transform(object, (result, value, key) => {
    if (!isEqual(value, base[key])) {
      result[key] = isObject(value) && isObject(base[key]) ? difference(value, base[key]) : value;
    }
  });
}
  1. 获取链接中参数列表
export function GetRequest(url) {
  if (!url || url.indexOf('?') == -1) {
    return {};
  }
  url = url.split('?')[1].split('#')[0]; //获取url中"?"符后"#"前的字串
  const theRequest = new Object();
  const str = decodeURI(url);
  const strs = void 0;
  if (str.indexOf("&") != -1) {
    strs = str.split("&");
    for (const i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
    }
  } else {
    theRequest[str.split("=")[0]] = decodeURIComponent(str.split("=")[1]);
  }

  return theRequest;
}
  1. 逗号拼接参数
export function getValue(obj) {
  return Object.keys(obj)
    .map(key => obj[key])
    .join(",");
}
  1. 格式化筛选参数
export function getFilters(filtersArg) {
  return Object.keys(filtersArg).reduce((obj, key) => {
    const newObj = { ...obj };
    newObj[key] = getValue(filtersArg[key]);
    return newObj;
  }, {});
}
  1. 数组对象深度克隆复制
export function objectClone(origin = {}, obj = {}) {
  for (const i in origin) {
    obj[i] = origin[i];
  }
  return obj;
}
export function arrayClone(origin = [], arr = []) {
  for (const i in origin) {
    if (typeof origin[i] !== "object") {
      arr.push(origin[i]);
    } else {
      arr.push(objectClone(origin[i]));
    }
  }
  return arr;
}
  1. 电子邮件验证
/**
 * 电子邮件
 * @type {RegExp}
 */
export const RegExpEmail = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
export function checkEmail(value, callback) {
  if (value && !RegExpEmail.test(value)) {
    callback("邮箱地址不正确");
  } else {
    callback();
  }
}
  1. 手机号码验证
/**
 * 手机号码
 * @type {RegExp}
 */
export const RegExpChinaMobileNumber = /^(?=\d{11}$)^1(?:3\d|4[57]|5[^4\D]|66|7[^249\D]|8\d|9[89])\d{8}$/;
export function checkMobileNumber(value, callback) {
  if (value && !RegExpChinaMobileNumber.test(value)) {
    callback("手机号码不正确");
  } else {
    callback();
  }
}
  1. base64解码、编码
/**
 * 
 * @param string
 */
let keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// 编码
const utf8_encode = function (string) {
  string = string.replace(/\r\n/g, "\n");
  let utftext = "";
  for (let n = 0; n < string.length; n++) {
    let c = string.charCodeAt(n);
    if (c < 128) {
      utftext += String.fromCharCode(c);
    } else if ((c > 127) && (c < 2048)) {
      utftext += String.fromCharCode((c >> 6) | 192);
      utftext += String.fromCharCode((c & 63) | 128);
    } else {
      utftext += String.fromCharCode((c >> 12) | 224);
      utftext += String.fromCharCode(((c >> 6) & 63) | 128);
      utftext += String.fromCharCode((c & 63) | 128);
    }

  }
  return utftext;
}
export const encodeFuc = function (input) {
  let output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
  input = utf8_encode(input);
  while (i < input.length) {
    chr1 = input.charCodeAt(i++);
    chr2 = input.charCodeAt(i++);
    chr3 = input.charCodeAt(i++);
    enc1 = chr1 >> 2;
    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
    enc4 = chr3 & 63;
    if (isNaN(chr2)) {
      enc3 = enc4 = 64;
    } else if (isNaN(chr3)) {
      enc4 = 64;
    }
    output = output +
      keyStr.charAt(enc1) + keyStr.charAt(enc2) +
      keyStr.charAt(enc3) + keyStr.charAt(enc4);
  }
  return output;
}

// 解码
const utf8_decode = function (utftext) {
  let string = "", i = 0, c = 0, c1 = 0, c2 = 0, c3 = 0;
  while (i < utftext.length) {
    c = utftext.charCodeAt(i);
    if (c < 128) {
      string += String.fromCharCode(c);
      i++;
    } else if ((c > 191) && (c < 224)) {
      c2 = utftext.charCodeAt(i + 1);
      string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
      i += 2;
    } else {
      c2 = utftext.charCodeAt(i + 1);
      c3 = utftext.charCodeAt(i + 2);
      string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
      i += 3;
    }
  }
  return string;
}
export const decodeFuc = function (input) {
  let output = "", chr1, chr2, chr3, enc1, enc2, enc3, enc4, i = 0;
  input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  while (i < input.length) {
    enc1 = keyStr.indexOf(input.charAt(i++));
    enc2 = keyStr.indexOf(input.charAt(i++));
    enc3 = keyStr.indexOf(input.charAt(i++));
    enc4 = keyStr.indexOf(input.charAt(i++));
    chr1 = (enc1 << 2) | (enc2 >> 4);
    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
    chr3 = ((enc3 & 3) << 6) | enc4;
    output = output + String.fromCharCode(chr1);
    if (enc3 != 64) {
      output = output + String.fromCharCode(chr2);
    }
    if (enc4 != 64) {
      output = output + String.fromCharCode(chr3);
    }
  }
  output = utf8_decode(output);
  return output;
}
  1. js数据类型的判断
export const getValueType = (data) => {
  let dataType = {
    '[object Null]': 'null',
    '[object Undefined]': 'undefined',
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regexp',
    '[object Object]': 'object',
    '[object Symbol]': 'symbol',
    '[object Map]': 'map',
    '[object Set]': 'set',
    '[object Int8Array]': 'int8array',
    '[object Error]': 'error'
  }
  return dataType[Object.prototype.toString.call(data)]
}
  1. 数组去重返回新数组
export const SetArray = (arr) => Array.from(new Set(arr));
  1. 函数防抖
/**
 * 
 * @param  {Fuc} fn
 * @param  {Number} duration
 */
export const debounce = (fn, duration) => {
  let timer = null
  let fns = () => {
    clearTimeout(timer)
    timer = setTimeout(fn, duration)
  }
  return fns
}
  1. 原生设置cookie
  /**
 * cookieJar
 */
export const cookie = {
  get: function (name) {
    return (name = RegExp("(^| )" + name + "=([^;]*)(;|$)").exec(document.cookie)) ? name[2] : null
  },
  /**
   * 设置 cookie
   * @param {string} name cookie name
   * @param {string} key  cookie value
   * @param {option} opt  {expire: 1000, domain: '', path: '', Ra: true}
   */
  set: function (name, key, opt) {
    var expireTime;
    opt.expire && (expireTime = new Date, expireTime.setTime(expireTime.getTime() + opt.expire));
    document.cookie = name + "=" + key
      + (opt.domain ? "; domain=" + opt.domain : "")
      + (opt.path ? "; path=" + opt.path : "")
      + (expireTime ? "; expires=" + expireTime.toGMTString() : "")
      + (opt.Ra ? "; secure" : "")
      ;
  }
}  
  1. 函数柯里化
/**
  * @param  {fn} Func
 * @param  {arr} Array
 */
export const fucCurry = ( fn, arr = []) => (...args) => ( a => a.length === fn.length ? fn(...a) : curry(fn, a))([...arr, ...args]);
  1. 控制时间
/**
 *  控制多久时间之后再往后执行
 *  @param  {Number} time
 */
export const controlAfterTime = time => new Promise(resolve => setTimeout(resolve, time));
  1. 删除对象的指定属性
/**
 * 
 * @param  {Object} object 比较来源
 * @param  {string} k  比较目标
 */
export const deleteKInObjOrAry = function (data, k) {
  if (getValueType(data) === 'object') {
   return Object.keys(data)
    .filter(key => key !== k)
    .map(key =>  {return {[key]: data[key]} })
    .reduce((accumulator, current) => 
      ({...accumulator, ...current}),
      {}
    )
  } else {
    return false;
  }
}