import isStr from './isStr';
import isUdf from './isUdf';
import isArr from './isArr';

/**
 * 根据路径获取对象属性
 * @param {*} object 目标对象
 * @param {string|string[]} path 属性路径，可以用'.'或'/'分隔或路径数组
 * @param {*} defaultVal 默认值，不传为undefine
 * @returns {*}
 *
 * const obj = {
 *   name: 'obj', bol: true, num: 0, ptn: /abc/,
 *   arr: [{ name: 'arr0' }, { name: 'arr2' }],
 *   subObj: { name: 'subObj', innerObj: { name: 'innerObj', age: 18 } }
 * }
 *
 * get(obj, 'name');                 // => 'obj'
 * get(obj, 'subObj.innerObj.name'); // => 'innerObj'
 * get(obj, 'subObj.innerObj.age');  // => 18
 * get(obj, 'subObj/outerObj/name'); // => undefined
 * get(obj, 'arr/0/name');           // => 'arr0'
 * get(obj, 'arr.1.age', 20);        // => 20
 * get(obj, 'arr.1.name', 'Tom');    // => 'arr2'
 * get(obj, 'bol.name');             // => 'undefined'
 */
function get(object, path, defaultVal) {
  if (isUdf(object) || !isStr(path) && !isArr(path)) {
    return defaultVal;
  }

  var paths = isStr(path) ? path.split(/\//.test(path) ? '/' : '.') : path;
  var pathList = paths.filter(function (p) {
    return !!p || p === 0;
  });
  var prop = pathList.shift();
  prop = isUdf(prop) ? '' : String(prop).replace(/^\s*|\s*$/g, '');

  if (!prop) {
    return object;
  }

  if (!object || typeof object !== 'object') {
    return defaultVal;
  }

  var value = object[prop];
  if (isUdf(value)) return defaultVal;
  return pathList.length ? get(value, pathList, defaultVal) : value;
}

export default get;
