utils.js 830 Bytes
Newer Older
1
function isObject(obj) {
邓晓峰's avatar
邓晓峰 committed
2
  return !!obj && typeof obj === 'object';
3 4 5
}

function objectify(thing) {
邓晓峰's avatar
邓晓峰 committed
6 7
  if (!isObject(thing)) return {};
  return thing;
8 9 10
}

function get(entity, path) {
邓晓峰's avatar
邓晓峰 committed
11 12 13 14
  let current = entity;
  for (let i = 0; i < path.length; i += 1) {
    if (current === null || current === undefined) {
      return undefined;
15
    }
邓晓峰's avatar
邓晓峰 committed
16 17 18
    current = current[path[i]];
  }
  return current;
19 20 21
}

function normalizeArray(arr) {
邓晓峰's avatar
邓晓峰 committed
22 23
  if (Array.isArray(arr)) return arr;
  return [arr];
24 25 26
}

function isFunc(thing) {
邓晓峰's avatar
邓晓峰 committed
27
  return typeof thing === 'function';
28 29 30
}

function inferSchema(thing) {
邓晓峰's avatar
邓晓峰 committed
31 32 33 34 35 36 37 38 39 40
  if (thing.schema) {
    return thing.schema;
  }
  if (thing.properties) {
    return {
      ...thing,
      type: 'object',
    };
  }
  return thing;
41 42 43
}

module.exports = {
邓晓峰's avatar
邓晓峰 committed
44 45 46 47 48 49 50
  isObject,
  objectify,
  get,
  normalizeArray,
  isFunc,
  inferSchema,
};