"use strict";

exports.__esModule = true;
exports.set = void 0;

/**
 * [createObj 创建对象]
 * @param  {string} key   [对象的属性名]    嵌套属性key用'.'来间隔
 * @param  {string}   value [对应属性值]
 * @return {object}       [创建新对象]
 * @access private
 * *****************************************************************
 * example :
 *  Frame.Utils.createObj("a.b.c",[1,2,3])  // result: {a:{b:{c:[1,2,3]}}}
 */
var createObj = function createObj(key, value) {
  var result = value;

  if (key) {
    var keyType = typeof key;
    var keys = keyType === 'array' ? key : key.split('.');

    for (var i = keys.length - 1; i >= 0; i--) {
      var newObj = {};
      newObj[keys[i]] = result;
      result = newObj;
    }
  }

  return result;
};
/**
 * ---
 * 设置对象或数组属性对应的值
 * * 主要用于深度获取未知对象的值.
 * @param object 需要呗设置的对象
 * @param {string} key  设置的key属性
 * @param {*} val  key对应的value值
 * @returns {object} 设置后的对象值
 * @static
 * @todo 后续继续扩展split和array
 * @function set
 * @example 01 设置属性值
 * --------------------------------------------------------------------------
 * import { set } from '@riil-frontend/utils';
 * const obj = { a: { b: { c: [{ }, { d: 'name' }] } } };
 * set(obj, 'a.b.c.1.d','newName');
 * // result
 * { a: { b: { c: [{ }, { d: 'newName' }] } } };
 * @example 01 设置不存在属性的值
 * --------------------------------------------------------------------------
 * set(obj, 'm.b.c.d','noProp');
 * // result
 *  { a: { b: { c: [{ }, { d: 'newName' }] } },
 *    m: { b: { c: { d: 'noProp' } } }
 *  };
 */


var set = function set(object, key, val) {
  var obj = object || {};

  if (typeof key === 'string') {
    var keys = key.split('.');
    var value = obj;

    for (var i = 0; i < keys.length; i++) {
      var _value = value[keys[i]];

      var _type = typeof _value;

      if (_type === 'object' || _type === 'array') {
        if (i === keys.length - 1) {
          value[keys[i]] = val;
          break;
        }

        value = value[keys[i]];
      } else {
        if (i === keys.length - 1) {
          value[keys[i]] = val;
          break;
        }

        var _keys = keys.slice(i + 1, keys.length);

        value[keys[i]] = createObj(_keys, val);
        break;
      }
    }
  }

  return obj;
};

exports.set = set;