@jedmao/storage
Version:
A Storage class that implements the Storage interface of the Web Storage API.
70 lines (69 loc) • 2.17 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Allows the addition, modification, or deletion of stored data items.
*/
// eslint-disable-next-line @typescript-eslint/class-name-casing
class Storage {
constructor() {
this.storage = new Map();
}
/**
* Returns an integer representing the number of data items stored in the
* `Storage` object.
*/
get length() {
return this.storage.size;
}
/**
* When invoked, will empty all keys out of the storage.
*/
clear() {
this.storage = new Map();
}
/**
* When passed a key name, will return that key's value.
* @returns the value of the key or `null` if the key does not exist.
*/
getItem(keyName) {
var _a;
return (_a = this.storage.get(keyName)) !== null && _a !== void 0 ? _a : null;
}
/**
* When passed a number `index`, this method will return the name of the
* nth key in the storage.
* @returns the value of the key or `null` if the key does not exist.
*/
key(
/**
* The number of the key for which you want the name. This is
* a zero-based value.
*/
index) {
var _a;
return (_a = Array.from(this.storage.keys())[+index || 0]) !== null && _a !== void 0 ? _a : null;
}
/**
* When passed a key name, will remove that key from the storage.
*/
removeItem(keyName) {
this.storage.delete(keyName);
}
/**
* When passed a key name and value, will add that key to the storage,
* or update that key's value if it already exists.
* @throws if the storage is full. Particularly, in Mobile Safari
* (Safari sets the quota to `0` bytes in private mode, unlike other browsers,
* which allow storage in private mode using separate data containers.)
* Hence developers should make sure to **always** catch possible exceptions
* from `setItem()`**.
*/
setItem(keyName,
/**
* The value is converted into a string.
*/
value) {
this.storage.set(keyName, value + '');
}
}
exports.Storage = Storage;