js 实用方法

58 阅读1分钟

tree to array 【扁平化数据】

/**
* tree to array 【扁平化数据】
* */
export const treeToArray = (data) => {
  return data.reduce((res,{children = [], ...params}) => {
    return res.concat([params],treeToArray(children))
  },[])
}

防抖

/**
 * 简单实现防抖方法
 *
 * 防抖(debounce)函数在第一次触发给定的函数时,不立即执行函数,而是给出一个期限值(delay),比如100ms。
 * 如果100ms内再次执行函数,就重新开始计时,直到计时结束后再真正执行函数。
 * 这样做的好处是如果短时间内大量触发同一事件,只会执行一次函数。
 *
 * @param fn 要防抖的函数
 * @param delay 防抖的毫秒数
 * @returns {Function}
 */
export function simpleDebounce(fn, delay = 500) {
  let timer = null
  return function () {
    let args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

获取指定时间范围内指定间隔天数的所有日期

/**
*
* 获取指定时间范围内指定间隔天数的所有日期
* getDateStr('2023-02-01', '2023-03-10', 0);
* */
export function getDateStr(startDate, endDate, dayLength) {
  let str = startDate;
  for (let i = 0 ;; i++) {
    let getDate = getTargetDate(startDate, dayLength);
    startDate = getDate;
    if (getDate <= endDate) {
      str += ','+getDate;
    } else {
      break;
    }
  }
  return str;
}
export function getTargetDate(date,dayLength) {
  dayLength = dayLength + 1;
  let tempDate = new Date(date);
  tempDate.setDate(tempDate.getDate() + dayLength);
  let year = tempDate.getFullYear();
  let month = tempDate.getMonth() + 1 < 10 ? "0" + (tempDate.getMonth() + 1) : tempDate.getMonth() + 1;
  let day = tempDate.getDate() < 10 ? "0" + tempDate.getDate() : tempDate.getDate();
  return year + "-" + month + "-" + day;
}