"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getCached = getCached;
var _isIdentical = _interopRequireDefault(require("../Array/isIdentical"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
var cache = new Map();

/**
 * A helper function to cache results of expensive functions (an alternative way of memoize)
 * @param {string} name
 * @param {...*} args
 */
function getCached(name) {
  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
    args[_key - 1] = arguments[_key];
  }
  var cachedItem = cache.get(name);
  var isValid = Boolean(cachedItem && (0, _isIdentical["default"])(args, cachedItem.args));
  return {
    /**
     * @return {boolean}
     */
    validate: function validate() {
      return isValid;
    },
    /**
     * @return {*}
     */
    getValue: function getValue() {
      return isValid && cachedItem.value || undefined;
    },
    /**
     * @param {*} value
     */
    setValue: function setValue(value) {
      cache.set(name, {
        args: args,
        value: value
      });
      return value;
    },
    /**
     * @param fn
     * @return {*}
     */
    use: function use(fn) {
      if (this.validate()) {
        return this.getValue();
      }
      return this.setValue(fn());
    }
  };
}