自己用的一些小函数们

146 阅读1分钟

针对后端不给我kv的情况~

酱:我的create/update入参只有id(s),detail接口就只给id(s)🙄

  processInitalVal(list: any[], id?: number, ids?: number[]): any {
    if (id) {
      const obj = (list || []).find(i => i.id === id);
      if (obj) {
        return {
          ...obj,
          key: obj.id,
          label: obj.name
        };
      }
    }
    if (ids) {
      const arr = (list || []).filter(i => ids.includes(i.id));
      if (arr?.length > 0) {
        return arr.map(i => ({
          ...i,
          key: i.id,
          label: i.userName
        }));
      }
    }
    return undefined;
  }

数组打平 && Find his father

黑心后端不给pid,想使用 tree search 要把数组打平🥱,就先这样吧~

flatten = (data, pid = '') => data.reduce((arr, {key, title, children = []}) =>
    arr.concat([{key, title, pid}], this.flatten(children, key)), [])

时间处理

/**
 * @description: hh:mm:ss
 * @param {number} timestamp 毫秒
 */
function timestamp2String(timestamp) {
  if (!timestamp) {
    return '-';
  }
  let leftTS = timestamp % (1000 * 3600);
  const h = Math.floor(timestamp / (1000 * 3600));
  leftTS %= (1000 * 60);
  const m = Math.floor(leftTS / (1000 * 60));
  const s = Math.round(leftTS / 1000);
  const filter = (num) => {
    if (num < 10) {
      return num === 0 ? '00' : `0${num}`;
    }
    return `${num}`;
  };
  return `${filter(h)}:${filter(m)}:${filter(s)}`;
}

a标签下载

async function downloadFile(url, name) {
  const a = document.createElement('a');
  a.href = window.URL.createObjectURL(new Blob([url]));
  document.body.appendChild(a);
  a.download = name;
  a.click();
  document.body.removeChild(a);
}