format.ts 1.4 KB
import { useCallback, useEffect, useRef } from 'react';

interface IArea {
  value: string;
  label: string;
  children?: IArea[];
}

// 省市区信息平铺
export const getAreaData = (data: IArea[]) => {
  let areaData: any = [];
  const eachArea = (items: IArea[]) => {
    items.map((item, i) => {
      areaData.push({
        value: item.value,
        label: item.label,
      });
      if (item.children) eachArea(item.children);
    });
  };
  eachArea(data);
  return areaData;
};

// 根据code数组和地区信息返回数组地区名称
export const getAreaNamesByCodes = (codes: string[], areaData: IArea[]) => {
  let names: any = [];
  const eachName = (items: IArea[]) => {
    items.map((item, i) => {
      if (codes.includes(item.value)) {
        names.push(item.label);
      }
    });
  };
  eachName(areaData);
  return names;
};

export function useDebounce(fn: any, delay: number) {
  const { current } = useRef({ fn, timer: null as unknown as NodeJS.Timeout });
  useEffect(
    function () {
      current.fn = fn;
    },
    [current.fn, fn],
  );

  return useCallback(
    function (...args: any[]) {
      if (current.timer) {
        clearTimeout(current.timer as unknown as number);
      }
      current.timer = setTimeout(() => {
        current.fn.call(current.fn, ...args);
      }, delay);
    },
    [current.fn, current.timer, delay],
  );
}