util.js 5.69 KB
// 手机正则
const REGEXPS = {
  "mobile": /^1\d{10}$/
}
// 验证手机
function checkMobile(str) {
  return REGEXPS.mobile.test(str);
}


/**
 * 链接参数转换为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, '":"') +
    '"}'
  )
}

/**
 * 格式化日期常规日期
 * 格式yyyy-MM-dd hh:mm:ss
 * @param {*} date
 */
function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

/**
 * 格式化数字,不足一位补充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 = wx.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 = wx.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;
}

/**
 * 获取点击传值
 * @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;
}

function rad(d) {
  return d * Math.PI / 180.0;
}

/**
 * 获取微信距离
 * @param {*} locationRes 当前位置
 * @param {*} targetPosition 目标位置
 */
function getLocalDistance(locationRes, targetPosition) {
  var lat1 = locationRes.latitude;
  var lng1 = locationRes.longitude;
  var lat2 = targetPosition.latitude;
  var lng2 = targetPosition.longitude;
  var radLat1 = rad(lat1);
  var radLat2 = rad(lat2);
  var a = radLat1 - radLat2;
  var b = rad(lng1) - rad(lng2);
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * 6378.137;

  // s:单位米
  s = Math.round(s * 10000);

  var kkm = 1000000,
    km = 1000;
  // dis:文字化单位
  var dis = s > kkm ? (s / kkm).toFixed(1) + "千公里" : (s > km ? (s / km).toFixed(1) + "公里" : s + "米");

  console.log("s:", s);
  console.log("dis:", dis);
  return {
    s,
    dis
  };
}

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


/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行,false 表非立即执行
 */
function debounce(func, wait, immediate) {
  let timeout;

  return function () {
    let context = this;
    let args = arguments;

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

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版,2 表定时器版
 * 时间戳版的函数触发是在时间段内开始的时候,而定时器版的函数触发是在时间段内结束的时候。
 */
function throttle(func, wait, type) {
  if (type === 1) {
    var previous = 0;
  } else if (type === 2) {
    var timeout;
  }
  return function () {
    let context = this;
    let args = arguments;
    if (type === 1) {
      let now = Date.now();

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

module.exports = {
  formatTime: formatTime,
  checkMobile: checkMobile,
  getLastScreenHeight: getLastScreenHeight,
  debounce: debounce,
  throttle: throttle,
  param2Obj: param2Obj,
  pxToRpx: pxToRpx,
  formatWeek: formatWeek,
  getBindtapData: getBindtapData,
  wxacodeGet: wxacodeGet,
  getObjByListKeyValue: getObjByListKeyValue,
  getLocalDistance: getLocalDistance
}