utils.js 2.16 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
// 判断是否是数字
export const isNumber = (val) => {
  const regPos = /^\d+(\.\d+)?$/; // 非负浮点数
  const regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; // 负浮点数
  return regPos.test(val) || regNeg.test(val);
};

// 创造guid
export const createGuid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
    .replace(/[xy]/g, (c) => {
      // eslint-disable-next-line no-bitwise
      const r = (Math.random() * 16) | 0;
      // eslint-disable-next-line no-bitwise
      const v = c === 'x' ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    })
    .toUpperCase();
};

// 深拷贝
export const deepCopy = (p, c) => {
  // eslint-disable-next-line no-param-reassign
  c = c || {};
  // eslint-disable-next-line no-restricted-syntax
  for (const i in p) {
    if (typeof p[i] === 'object') {
      // eslint-disable-next-line no-param-reassign
      c[i] = p[i].constructor === Array ? [] : {};
      deepCopy(p[i], c[i]);
    } else {
      // eslint-disable-next-line no-param-reassign
      c[i] = p[i];
    }
  }
  return c;
};

// rgba颜色转换
export const hexToRgba = (hex, opacity) => {
  // eslint-disable-next-line no-param-reassign
  hex = hex || '#808080';
  // eslint-disable-next-line no-param-reassign
  opacity = opacity !== undefined ? opacity : 1;
  // eslint-disable-next-line radix
  return `rgba(${parseInt(`0x${hex.slice(1, 3)}`)}, ${parseInt(`0x${hex.slice(3, 5)}`)}, ${parseInt(
    `0x${hex.slice(5, 7)}`,
  )}, ${opacity})`;
};

// 加法运算
export const addNumMethod = (num1, num2) => {
  let sq1;
  let sq2;
  let m;
  try {
    sq1 = num1.toString().split('.')[1].length;
  } catch (e) {
    sq1 = 0;
  }
  try {
    sq2 = num2.toString().split('.')[1].length;
  } catch (e) {
    sq2 = 0;
  }
  // eslint-disable-next-line prefer-const
  m = Math.max(sq1, sq2);
  return (num1 + num2).toFixed(m);
};

// 进制转换
export const hexSwitch = (num, m, n) => {
  const s = `${num}`;
  const result = parseInt(s, m).toString(n);
  return result;
};

// 文本样式
export const textStyle = () => {
  return {
    font: 'bold 11pt Helvetica, Arial, sans-serif',
    stroke: 'whitesmoke',
  };
};