数据mock简易版

51 阅读1分钟

const MockData = (data = {}, arrLen = 10) => {
  const keys = Object.keys(data);
  const obj = Array.isArray(data) ? [] : {};
  for (let i of keys) {
    const type = Object.prototype.toString.call(data[i]);
    if (type === "[object String]") {
      obj[i] = getRandomChineseWord(2, 4);
    } else if (type === "[object Number]") {
      obj[i] = getRandomInt(0, 615732);
    } else if (type === "[object Boolean]") {
      obj[i] = getRandomBoolean();
    } else if (type === "[object Object]") {
      obj[i] = MockData(data[i]);
    } else if (type === "[object Array]") {
      obj[i] = Array.from(new Array(getRandomInt(1, arrLen)), () =>
        MockData(data[i][0])
      );
    }
  }
  return obj;
};

const getRandomInt = (min = 0, max = min + 1) =>
  Math.round(Math.random() * (max - min)) + min;
const getRandomBoolean = () => (Math.random() > 0.5 ? true : false);
const getRandomChineseWord = (min = 0, max = 1) => {
  let res = "";
  const num = getRandomInt(min, max);
  for (let i = 0; i < num; i++) {
    const randomUniCode = Math.floor(
      Math.random() * (40870 - 19968) + 19968
    ).toString(16);
    eval("res +=" + '"\\u' + randomUniCode + '"');
  }
  return res;
};