"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ObjectDriller = void 0;

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

/**
 * A type-safe way to drill down into an object and gather the associated path
 * NOTE: ObjectDriller is only for accessing data. The underlying `obj` should
 * never be mutated directly.
 */
var ObjectDriller = /*#__PURE__*/function () {
  function ObjectDriller(obj, path) {
    _classCallCheck(this, ObjectDriller);

    _defineProperty(this, "value", void 0);

    _defineProperty(this, "arrayValue", void 0);

    _defineProperty(this, "path", void 0);

    this.value = obj;
    this.arrayValue = this.value;
    this.path = path || '';
  }
  /**
   * Drill down into the object by specifying the next field
   * @param field A field on the data object
   */


  _createClass(ObjectDriller, [{
    key: "at",
    value: function at(field) {
      // eslint-disable-next-line eqeqeq
      if (this.value == undefined) {
        // checks null or undefined
        if (typeof field === 'number') {
          this.value = [];
        } else {
          this.value = _defineProperty({}, field, undefined);
        }
      }

      var subObj = this.value[field];
      var newPath = this.path === '' ? '' + field : "".concat(this.path, ".").concat(field);
      return new ObjectDriller(subObj, newPath);
    }
  }, {
    key: "find",
    value: function find(func) {
      // Instantiate the array if it does not exist
      // eslint-disable-next-line eqeqeq
      if (this.arrayValue == undefined) {
        // checks null or undefined
        this.arrayValue = [];
      }

      var idx = this.arrayValue.findIndex(func); // Add new element to end of array if item does not exist

      idx = idx < 0 ? this.arrayValue.length : idx;
      var newPath = this.path === '' ? '' + idx : "".concat(this.path, ".").concat(idx);
      var subObj = this.arrayValue[idx];
      return new ObjectDriller(subObj, newPath);
    }
  }]);

  return ObjectDriller;
}();

exports.ObjectDriller = ObjectDriller;