前端非常好用的常用方法

import { useRef, useEffect, useCallback } from "react";


/**
 * 解析html文本
 * @ctype PROCESS
 * @description 解析html文本
 * @param {string} htmlText html文本
 * @returns
 * el HTMLElement html节点
 */
function parseHtml(htmlText) {
  let el = document.createElement('div');
  el.innerHTML = htmlText;
  return el.children[0];
}


/**
 * @description: 函数节流,普通防连点
 * @param {(Function, number?)}
 * @return {Function}
 */
const _throttle = (fun, delay = 2000) => {
  let last, deferTimer;
  return function () {
    const now = +new Date();
    if (last && now < last + delay) {
      clearTimeout(deferTimer);
      deferTimer = setTimeout(() => {
        last = now;
      }, delay);
    } else {
      last = now;
      fun.apply(this, arguments);
    }
  };
};


/**
 * @description: 函数节流,hooks
 * @param {(Function, number?)}
 * @return {Function}
 */
function useThrottle(fn, delay = 2000, dep = []) {
  const { current } = useRef({ fn, timer: null });
  useEffect(function () {
    current.fn = fn;
  }, [fn]);

  return useCallback(function f(...args) {
    if (!current.timer) {
      current.timer = setTimeout(() => {
        delete current.timer;
      }, delay);
      current.fn.call(this, ...args);
    }
  }, dep);
}

/**
 * @description: 函数防抖
 * @param {(Function, number?, boolean? )}
 * @return {Function}
 */
const _debounce = (fn, wait = 2000, immediate = false) => {
  let timer = null
  return function () {
    const later = function () {
      fn.apply(this, arguments)
    }
    if (immediate && !timer) {
      later()
    }
    if (timer) clearTimeout(timer)
    timer = setTimeout(later, wait)
  }
}

/**
 * 获取cookie的值
 * @param {*} cookieName
 */
function getCookie(cookieName) {
  const strCookie = document.cookie;
  const arrCookie = strCookie.split('; ');
  for (let i = 0; i < arrCookie.length; i++) {
    const arr = arrCookie[i].split('=');
    if (cookieName == arr[0]) {
      return arr[1];
    }
  }
  return '';
}

/**
 * 获取url参数
 * @param {string} name
 */
function getUrlParam(name) {
  const search = window.location.search;
  const matched = search
    .slice(1)
    .match(new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'));
  return search.length ? matched && matched[2] : null;
}

/**
 * 删除url中的参数
 * @param {*} url
 * @param {*} arg
 */
function delUrlParam(url, ref) {
  // 如果不包括此参数
  if (url.indexOf(ref) == -1) return url;

  const arr_url = url.split('?');
  const base = arr_url[0];
  const arr_param = arr_url[1].split('&');
  let index = -1;

  for (let i = 0; i < arr_param.length; i++) {
    const paired = arr_param[i].split('=');
    if (paired[0] == ref) {
      index = i;
      break;
    }
  }
  if (index == -1) {
    return url;
  } else {
    arr_param.splice(index, 1);
    return base + '?' + arr_param.join('&');
  }
}

/**
 * 日期格式化
 * @param date    接收可以被new Date()方法转换的内容
 * @param format  字符串,需要的格式例如:'yyyy/MM/dd hh:mm:ss'
 * @returns {String}
 */
const dateFormatter = (date, format = "yyyy/MM/dd") => {
  if (!date) return "-";
  date = new Date(
    typeof date === "string" && isNaN(date)
      ? date.replace(/-/g, "/")
      : Number(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(format)) {
    format = format.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (const k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return format;
};

/** 时间格式化 */
const dealTime = (msTime) => {
  const time = msTime / 1000;
  let hour = Math.floor(time / 60 / 60) % 24;
  let minute = Math.floor(time / 60) % 60;
  let second = Math.floor(time) % 60;
  hour = hour > 9 ? hour : "0" + hour;
  minute = minute > 9 ? minute : "0" + minute;
  second = second > 9 ? second : "0" + second;
  return `${minute}:${second}`;
}


/**
 *  xxxx秒->1天2时3分4秒
 * @param {*} msTime 
 */
const dateDuration = (second) => {
  var duration = ""
  var days = Math.floor(second / 86400);
  var hours = Math.floor((second % 86400) / 3600);
  var minutes = Math.floor(((second % 86400) % 3600) / 60);
  var seconds = Math.floor(((second % 86400) % 3600) % 60);
  if (days > 0) duration = days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";
  else if (hours > 0) duration = hours + "小时" + minutes + "分钟" + seconds + "秒";
  else if (minutes > 0) duration = minutes + 1 + "分钟"
  else if (seconds > 0) duration = 1 + "分钟";
  return duration;
}


/**
 * 转换k
 * @param {*} num
 */
function getThousandToK(num) {
  let s_x;
  if (num >= 1000) {
    let result = num / 1000;
    result = Math.floor(result * 10) / 10;
    s_x = result.toString();
    let pos_decimal = s_x.indexOf(".");
    if (pos_decimal < 0) {
      pos_decimal = s_x.length;
      s_x += ".";
    }
    while (s_x.length <= pos_decimal + 1) {
      s_x += "0";
    }
    s_x += "k";
  } else {
    s_x = num;
  }
  return s_x;
}


/**
 * @description 处理字符串长度
 * @param str 字符串 
 * @param count 位数 默认5个
 */
const getHandleStr = (str, count = 5) => {
  if (typeof str !== 'string') {
    return
  }
  let s = str.toString()
  if (str.length <= count) {
    return s
  }
  s = s.substring(0, count) + '...'
  return s
}


/**
 * 截取字符串 中2英1
 * @param {*} str 
 * @param {*} sub_length 
 */
function subStringCE(str, sub_length) {
  const temp1 = str.replace(/[^\x20-\xff]/g, "**");
  const temp2 = temp1.substring(0, sub_length);
  const x_length = temp2.split("*").length - 1;
  const hanzi_num = x_length / 2;
  sub_length = sub_length - hanzi_num;
  const res = str.substring(0, sub_length);
  let endStr;
  if (sub_length < str.length) {
    endStr = res + "...";
  } else {
    endStr = res;
  }
  return endStr;
}


/**
 * 随机打乱数组
 * @param {*} arr 
 * @returns 
 */
function shuffleArr(arr) {
  for (let i = arr.length - 1; i >= 0; i--) {
    const randomIndex = Math.floor(Math.random() * (i + 1))
    const itemAtIndex = arr[randomIndex]
    arr[randomIndex] = arr[i]
    arr[i] = itemAtIndex
  }
  return arr
}


/**
 *  获取区间随机数 [min,max)
 * @export
 * @param {*} min
 * @param {*} max
 * @return {*} 
 */
function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min)) + min
}


/**
 *  数据扁平化
 * @export
 * @param {*} arr
 * @return {*} 
 */
function flatten(arr) {
  return arr.reduce((result, item) => {
    return result.concat(Array.isArray(item) ? flatten(item) : item)
  }, [])
}

/** 判断两个对象相等 */
const check2Object = (obj1, obj2) => {
  const o1 = obj1 instanceof Object
  const o2 = obj2 instanceof Object
  if (!o1 || !o2) { /*  判断不是对象  */
    return obj1 === obj2
  }
  if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false
  }
  for (const attr in obj1) {
    const t1 = obj1[attr] instanceof Object
    const t2 = obj2[attr] instanceof Object
    if (t1 && t2) {
      return check2Object(obj1[attr], obj2[attr])
    } else if (obj1[attr] !== obj2[attr]) {
      return false
    }
  }
  return true
}


/**
 * 添加内容到剪切板
 * @param {*} text 要添加到剪切板的内容
 */
function copyTxt(text) {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text).then(function () {
      console.log("已复制请打开浏览器查看")
    }, function () {
      const input = document.createElement("INPUT");
      input.value = text;
      input.className = "";
      document.body.appendChild(input);
      input.select();
      if (document.execCommand('copy')) {
        document.execCommand('copy');
      }
      document.body.removeChild(input);
      console.log("已复制请打开浏览器查看")
    });
  } else {
    const input = document.createElement("INPUT");
    input.value = text;
    input.className = "";
    document.body.appendChild(input);
    input.select();
    if (document.execCommand('copy')) {
      document.execCommand('copy');
    }
    document.body.removeChild(input);
    console.log("已复制请打开浏览器查看")
  }
}


/**
 * 秒转时间对象
 * @param {Number} totalSecond 总秒数
 * @return {{
 *  day: String,
 *  hour: String,
 *  minute: String,
 *  second: String
 * }}
 */
const second2Date = (totalSecond) => {
  const millisecond = totalSecond % 1000
  totalSecond = totalSecond / 1000

  // 获得总分钟数
  const totalMinute = totalSecond / 60
  // 获得剩余秒数
  const second = totalSecond % 60
  // 获得小时数
  const totalHour = totalMinute / 60
  // 获得分钟数
  const minute = totalMinute % 60
  // 获得天数
  const day = totalHour / 24
  // 获得剩余小时数
  const hour = totalHour % 24
  // 格式化的键值
  const includesKey = ['month', 'day', 'hour', 'minute', 'second', 'totalHour', 'totalMinute']
  // 日期对象
  const dateObj = { day, hour, minute, second, millisecond, totalHour, totalMinute }

  return Object.keys(dateObj).reduce((preVal, key) => {
    // 值取整
    const value = parseInt(dateObj[key])

    if (includesKey.includes(key) && value < 10) {
      if (value < 0) {
        preVal[key] = '00'
      } else {
        preVal[key] = '0' + value
      }
    } else {
      if (value.toString() === 'NaN') {
        preVal[key] = '0'
      } else {
        preVal[key] = value.toString()
      }
    }

    return preVal
  }, {})
}

/**
 * 等待一段时间再执行
 * @param {number} time 等待的时间ms
 */
function waitTime(time) {
  return new Promise(resolve => setTimeout(resolve, time))
}

/** 控制滚动--兼容ios */
const bodyScroll = (event) => {
  event.preventDefault();
}

const onCtrScroll = (flag = true) => {
  if (flag) { // 禁止滚动
    document.body.addEventListener('touchmove', bodyScroll, { passive: false });
  } else { // 开启滚动
    document.body.removeEventListener('touchmove', bodyScroll, { passive: false });
  }
}



/**
 * 超过1千米展示小数点保留一位的千米单位,如果小于1千米,展示米
 */
const distanceText = (val) => {
  if ((val / 1000) > 1) {
    return parseFloat((val / 1000).toFixed(1)) + '公里'
  } else {
    return Math.round(val) + '米'
  }
}
//获取当前年月日时分秒
const getNowTime = () => {
  let now = new Date();
  let year = now.getFullYear(); //获取完整的年份(4位,1970-????)
  let month = now.getMonth() + 1; //获取当前月份(0-11,0代表1月)
  let today = now.getDate(); //获取当前日(1-31)
  let hour = now.getHours(); //获取当前小时数(0-23)
  let minute = now.getMinutes(); //获取当前分钟数(0-59)
  let second = now.getSeconds(); //获取当前秒数(0-59)
  let nowTime = '';
  nowTime = year + '-' + (month < 10 ? '0' + month : month) + '-' + (today < 10 ? '0' + today : today) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' +
    (minute < 10 ? '0' + minute : minute) + ':' + (second < 10 ? '0' + second : second)
  return nowTime
};

//对象去重
const uniq = (arr, key) => {
  const map = new Map();
  const newArr = arr.filter(v => !map.has(v[key]) && map.set(v[key], v));
  return newArr
}


/**
 * 标记出字符串中的指定字符
 * @param {*} str 要标记查找的字符串
 * @param {*} label 需要标记的文本
 * @param {*} color 自定义颜色
 * @returns 
 */
const dimstyleStrColor = (str, label, color) => {
  var reg = new RegExp("(" + label + ")", "g");
  var newstr = str.replace(reg, "<font color=" + color + ">$1</font>");
  return newstr
}

/**
 * 
 * @param {*} version1 版本号1
 * @param {*} version2 版本号2
 * @returns 比较结果 1=>大于 -1=>小于 0=>等于
 */
const compareVersion = (version1, version2) => {
  const arr1 = version1.split('.')
  const arr2 = version2.split('.')
  const length1 = arr1.length
  const length2 = arr2.length
  const minlength = Math.min(length1, length2)
  let i = 0
  for (i; i < minlength; i++) {
    let a = parseInt(arr1[i])
    let b = parseInt(arr2[i])
    if (a > b) {
      return 1
    } else if (a < b) {
      return -1
    }
  }
  if (length1 > length2) {
    for (let j = i; j < length1; j++) {
      if (parseInt(arr1[j]) != 0) {
        return 1
      }
    }
    return 0
  } else if (length1 < length2) {
    for (let j = i; j < length2; j++) {
      if (parseInt(arr2[j]) != 0) {
        return -1
      }
    }
    return 0
  }
  return 0
}


/**
 * 
 * @param {*} price 金额
 * @returns 1000 => 1,000
 */
function formatPrice(price) {
  return String(price).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值