util.js 8.8 KB
// 正则
const REGEXPS = {
  "mobile": /^1\d{10}$/,
  //身份证号码为15位或者18位,15位时全为数字,18位前17位为数字,最后一位是校验位,可能为数字或字符X。
  "identNo": /(^\d{15}$)|(^\d{17}([0-9]|X)$)/,
}
// 验证手机
function checkMobile(str) {
  return REGEXPS.mobile.test(str);
}

// 验证身份证
function checkIdentNo(num) {
  num = num.toUpperCase();
  return REGEXPS.identNo.test(num);
}

// 数组打乱顺序
function randomSort(a, b) {
  return Math.random() > 0.5 ? -1 : 1;
}

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}


//普通生成uuid
function uuid() {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";

  var uuid = s.join("");
  return uuid;
}

// 数组去重
function uniqueArray(arr) {
  return arr.reduce((result, item) => {
    const duplicate = result.find(obj => JSON.stringify(obj) === JSON.stringify(item));
    if (!duplicate) {
      result.push(item);
    }
    return result;
  }, []);
}

// 模拟分页
function paginateArray(arr, page, size = 10) {
  const startIndex = (page - 1) * size;
  const endIndex = startIndex + size;
  const currentPageList = arr.slice(startIndex, endIndex);
  const totalPages = Math.ceil(arr.length / size);

  return {
    list: currentPageList,
    totalPages
  };
}

/**
 * 链接参数转换为obj
 * 入参 完整链接
 * @param {*} url
 */
function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
    .replace(/"/g, '\\"')
    .replace(/&/g, '","')
    .replace(/=/g, '":"') +
    '"}'
  )
}


/**
 * 分转元
 * @param {*} fen
 * @returns
 */
export const regFenToYuan = (fen) => {
  var num = fen;
  num = fen * 0.01;
  num += '';
  var reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;
  num = num.replace(reg, '$1');
  num = toDecimal2(num)
  return num
};

/**
 * 元转分
 * @param {*} yuan
 * @param {*} digit
 * @returns
 */
export const regYuanToFen = (yuan, digit = 100) => {
  var m = 0,
    s1 = yuan.toString(),
    s2 = digit.toString();
  try {
    m += s1.split(".")[1].length
  } catch (e) {}
  try {
    m += s2.split(".")[1].length
  } catch (e) {}
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}

/**
 * 强制保留2位小数,如:2,会在2后面补上00.即2.00
 * @param {*} x
 * @returns
 */
export const toDecimal2 = (x) => {
  var f = parseFloat(x);
  if (isNaN(f)) {
    return false;
  }
  var f = Math.round(x * 100) / 100;
  var s = f.toString();
  var rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + 2) {
    s += '0';
  }
  return s;
}

/**
 * 格式化数字,不足一位补充0
 * @param {*} n
 */
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 获取屏幕剩余高度
 * useHeight 单位是rpx
 * 默认返回单位是rpx  可通过unit参数改为 px
 */
function getLastScreenHeight(useHeight = 0, unit = 'rpx') {
  let sysInfo = my.getSystemInfoSync();
  let clientHeight = sysInfo.windowHeight;
  // 获取可使用窗口高度
  let clientWidth = sysInfo.windowWidth;
  // 算出比例
  let ratio = 750 / clientWidth;
  // 算出屏幕高度(单位rpx)
  let height = clientHeight * ratio;
  // 计算剩余高度
  let lastHeight = height - useHeight;
  // 可转换成px
  if (unit == 'px') {
    lastHeight = lastHeight / 750 * clientWidth
  }
  return lastHeight;
}


/**
 * px转rpx
 * @param {*} value
 */
function pxToRpx(value) {
  let sysInfo = my.getSystemInfoSync();
  let clientWidth = sysInfo.windowWidth;
  let result = value / 750 * clientWidth
  return result;
}


// 格式化星期几
function formatWeek(week) {
  let result = "";
  switch (week) {
    case 1:
      result = "一";
      break;
    case 2:
      result = "二";
      break;
    case 3:
      result = "三";
      break;
    case 4:
      result = "四";
      break;
    case 5:
      result = "五";
      break;
    case 6:
      result = "六";
      break;
    case 0:
      result = "日";
      break;

    default:
      break;
  }
  return result;
}

/**
 * 格式化日期时间 支持Date和时间戳
 * @param {date} date 日期时间
 * @param {string} fmt 格式,如:'yyyy-MM-dd hh:mm:ss'
 */
function formatDate(date, fmt) {
  if (!date) return '-'
  // 把-换成/ 避免iOS和安卓真机问题

  if (isNaN(date)) {
    var reg = /-/g;
    date = date && date.replace(reg, '/');
  }

  date = new Date(date)
  const o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (const k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  }
  return fmt
}



/**
 * 获取点击传值
 * @param {*} evt
 * @param {*} key
 */
function getBindtapData(evt, key = "data") {
  let keyStr = key || "data";
  return evt.currentTarget.dataset[keyStr];
}

/**
 * 从数组中获取 key未value的对象
 * @param {*} value
 * @param {*} key
 * @param {*} list
 */
function getObjByListKeyValue(value, key, list) {
  let result = null;
  list.forEach(element => {
    if (element[key + ""] == value) {
      result = element;
    }
  });
  return result;
}

/**
 * 获取小程序码
 * path = "/pages/index/index?pa=1"
 * @param {*} path
 */
function wxacodeGet(path) {
  return "  https://api.k.wxpai.cn/bizproxy/mzcfsapi/qrcode/create?path=" + encodeURIComponent(path);
}

/**
 * 根据url获取参数
 * @param {*} name
 */
function getQueryByUrl(name, url) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ""])[1].replace(/\+/g, '%20')) || null;
}


/**
 * 添加base前缀(my.arrayBufferToBase64方法不提供前缀)
 */
function addBase64Prefix(base64) {
  return "data:image/PNG;base64," + base64;
}


/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行,false 表非立即执行
 */
let debounceTimeout;

function debounce(func, wait, immediate) {
  return function () {
    let context = this;
    let args = arguments;

    if (debounceTimeout) clearTimeout(debounceTimeout);
    if (immediate) {
      var callNow = !debounceTimeout;
      debounceTimeout = setTimeout(() => {
        debounceTimeout = null;
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      debounceTimeout = setTimeout(function () {
        func.apply(context, args)
      }, wait);
    }
  }();
}

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版,2 表定时器版
 * 时间戳版的函数触发是在时间段内开始的时候,而定时器版的函数触发是在时间段内结束的时候。
 */
let throttleTimeout;
let throttlePrevious;

function throttle(func, wait, type) {
  if (type === 1) {
    throttlePrevious = 0;
  } else if (type === 2) {
    throttleTimeout = 0;
  }
  return function () {
    let context = this;
    let args = arguments;
    if (type === 1) {
      let now = Date.now();

      if (now - throttlePrevious > wait) {
        func.apply(context, args);
        throttlePrevious = now;
      }
    } else if (type === 2) {
      if (!throttleTimeout) {
        throttleTimeout = setTimeout(() => {
          throttleTimeout = null;
          func.apply(context, args)
        }, wait)
      }
    }
  }();
}


module.exports = {
  shuffleArray: shuffleArray,
  randomSort: randomSort,
  uuid: uuid,
  uniqueArray: uniqueArray,
  paginateArray: paginateArray,
  formatDate: formatDate,
  formatNumber: formatNumber,
  checkMobile: checkMobile,
  checkIdentNo: checkIdentNo,
  getLastScreenHeight: getLastScreenHeight,
  debounce: debounce,
  throttle: throttle,
  param2Obj: param2Obj,
  pxToRpx: pxToRpx,
  formatWeek: formatWeek,
  getBindtapData: getBindtapData,
  wxacodeGet: wxacodeGet,
  getObjByListKeyValue: getObjByListKeyValue,
  getQueryByUrl: getQueryByUrl,
  regFenToYuan: regFenToYuan,
  regYuanToFen: regYuanToFen,
  toDecimal2: toDecimal2,
  addBase64Prefix: addBase64Prefix,
}