"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

var _immutable = require("immutable");

var _every = _interopRequireDefault(require("lodash/every"));

var _isObject = _interopRequireDefault(require("lodash/isObject"));

var _MultiWeakMap = _interopRequireDefault(require("./MultiWeakMap"));

/* eslint "no-param-reassign": "warn" */
// This is a method decorator that helps the stateHelper perform caching via
// WeakMaps. It accepts a function which returns a list of paths to pieces of
// the global Redux store, e.g., ['quizEntries']. It then looks up the value
// being stored in this path and checks to see if the decorated method has been
// called before with the same value, and if so, returns the cached result.
var _default = function _default(fnToGetPaths) {
  return function (target, name, descriptor) {
    var decoratedMethod = descriptor.value;
    var cache;

    descriptor.value = function () {
      var paths = fnToGetPaths(this);
      cache = cache || new _MultiWeakMap.default(paths.length + 1);
      var state = this.state();
      var fields = paths.map(function (path) {
        return state.getIn(path, (0, _immutable.Map)());
      });
      var keys = [this].concat(fields);

      if (cache.has(keys)) {
        return cache.get(keys);
      }

      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      var result = decoratedMethod.apply(this, args);

      if (allAreObjects(fields)) {
        cache.set(keys, result);
      }

      return result;
    };

    return descriptor;
  };
};

exports.default = _default;

var allAreObjects = function allAreObjects(values) {
  return (0, _every.default)(values, _isObject.default);
};