/* eslint-disable no-prototype-builtins */
export default function storageFactory(storage) {
  var inMemoryStorage = {};
  var length = 0;

  function isSupported() {
    try {
      var testKey = "__some_random_key__";
      storage.setItem(testKey, testKey);
      storage.removeItem(testKey);
      return true;
    } catch (e) {
      return false;
    }
  }

  function clear() {
    if (isSupported()) {
      storage.clear();
    } else {
      inMemoryStorage = {};
    }
  }

  function getItem(name) {
    if (isSupported()) {
      return storage.getItem(name);
    }

    if (inMemoryStorage.hasOwnProperty(name)) {
      return inMemoryStorage[name];
    }

    return null;
  }

  function key(index) {
    if (isSupported()) {
      return storage.key(index);
    }

    return Object.keys(inMemoryStorage)[index] || null;
  }

  function removeItem(name) {
    if (isSupported()) {
      storage.removeItem(name);
    } else {
      delete inMemoryStorage[name];
    }
  }

  function setItem(name, value) {
    if (isSupported()) {
      storage.setItem(name, value);
    } else {
      inMemoryStorage[name] = value;
    }
  }

  return {
    getItem: getItem,
    setItem: setItem,
    removeItem: removeItem,
    clear: clear,
    key: key,
    length: length,
    isSupported: isSupported
  };
}
export var getStorageInstance = function getStorageInstance() {
  var storage;

  try {
    storage = storageFactory(localStorage);
  } catch (e) {
    try {
      storage = storageFactory(sessionStorage);
    } catch (e2) {
      storage = storageFactory(storage = {
        setItem: function setItem() {
          throw new Error();
        },
        getItem: function getItem() {
          throw new Error();
        },
        isSupported: function isSupported() {
          return false;
        }
      });
    }
  }

  return storage;
};