"use strict";

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

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

require("core-js/modules/web.dom.iterable");

var _stringify = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/json/stringify"));

var _getPrototypeOf = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/get-prototype-of"));

var _defineProperties = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/object/define-properties"));

// 定义搜索历史记录 通用类
var searchHistory = function searchHistory(length, store) {
  var list = JSON.parse(localStorage.getItem(store)) || [];
  var ids = [];

  if (list.length) {
    list.forEach(function (item) {
      return ids.push(item.search_word);
    });
  }

  (0, _defineProperties.default)(list, {
    pop: {
      value: function value() {
        (0, _getPrototypeOf.default)(list).pop.call(list);
        ids.pop();
      }
    },
    splice: {
      value: function value() {
        var _Object$getPrototypeO;

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

        (_Object$getPrototypeO = (0, _getPrototypeOf.default)(list).splice).call.apply(_Object$getPrototypeO, [list].concat(args));

        ids.splice.apply(ids, args);
      }
    },
    unshift: {
      value: function value(val) {
        (0, _getPrototypeOf.default)(list).unshift.call(list, val);
        ids.unshift(val.search_word);
      }
    }
  });
  var history = {
    list,
    ids,

    get limit() {
      return length;
    },

    get length() {
      return this.list.length;
    },

    get(searchWord) {
      var idx = this.ids.indexOf(searchWord);
      if (idx === -1) return {};
      return this.list[idx];
    },

    append(val, save) {
      if (save === void 0) {
        save = true;
      }

      // this.remove(val, false);
      this.list.unshift(val);

      if (this.length > this.limit) {
        this.expel(false);
      }

      save && this.save();
    },

    expel(save) {
      this.list.pop();
      save && this.save();
    },

    remove(val, save) {
      if (save === void 0) {
        save = true;
      }

      var idx = this.ids.indexOf(val.search_word);
      if (idx === -1) return; // this.list.splice(idx, 1);

      this.list = this.list.filter(function (item) {
        return item.search_word !== val.search_word;
      });
      save && this.save();
    },

    save() {
      localStorage.setItem(store, (0, _stringify.default)(this.list));
    },

    clear() {
      this.list = [];
      this.ids = [];
      localStorage.removeItem(store);
    }

  };
  return history;
};

var _default = searchHistory;
exports.default = _default;