Storage Utilities
Utility functions for storage operations
IntermediateTopic: LocalStorage/SessionStorage
JavaScript Storage Utilities Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Method 1: Storage helper class
class StorageUtil {
constructor(storage = localStorage) {
this.storage = storage;
}
set(key, value) {
try {
this.storage.setItem(key, JSON.stringify(value));
return true;
} catch (e) {
console.error('Storage error:', e);
return false;
}
}
get(key, defaultValue = null) {
try {
const item = this.storage.getItem(key);
return item ? JSON.parse(item) : defaultValue;
} catch (e) {
console.error('Parse error:', e);
return defaultValue;
}
}
remove(key) {
this.storage.removeItem(key);
}
clear() {
this.storage.clear();
}
has(key) {
return this.storage.getItem(key) !== null;
}
keys() {
return Object.keys(this.storage);
}
size() {
let total = 0;
for (let key in this.storage) {
if (this.storage.hasOwnProperty(key)) {
total += this.storage[key].length + key.length;
}
}
return total;
}
}
const storage = new StorageUtil();
storage.set('name', 'John');
console.log('Name:', storage.get('name'));
console.log('Has name:', storage.has('name'));
console.log('Keys:', storage.keys());
// Method 2: Storage with expiration
class ExpiringStorage {
set(key, value, ttl) {
const item = {
value: value,
expiry: Date.now() + ttl
};
localStorage.setItem(key, JSON.stringify(item));
}
get(key) {
const itemStr = localStorage.getItem(key);
if (!itemStr) return null;
const item = JSON.parse(itemStr);
if (Date.now() > item.expiry) {
localStorage.removeItem(key);
return null;
}
return item.value;
}
clearExpired() {
const now = Date.now();
for (let i = localStorage.length - 1; i >= 0; i--) {
const key = localStorage.key(i);
const itemStr = localStorage.getItem(key);
try {
const item = JSON.parse(itemStr);
if (item.expiry && now > item.expiry) {
localStorage.removeItem(key);
}
} catch (e) {
// Not an expiring item, skip
}
}
}
}
const expiringStorage = new ExpiringStorage();
expiringStorage.set('token', 'abc123', 3600000); // 1 hour
console.log('Token:', expiringStorage.get('token'));
// Method 3: Namespaced storage
class NamespacedStorage {
constructor(namespace) {
this.namespace = namespace + ':';
}
set(key, value) {
localStorage.setItem(this.namespace + key, JSON.stringify(value));
}
get(key, defaultValue = null) {
const item = localStorage.getItem(this.namespace + key);
return item ? JSON.parse(item) : defaultValue;
}
remove(key) {
localStorage.removeItem(this.namespace + key);
}
clear() {
const keys = Object.keys(localStorage);
keys.forEach(key => {
if (key.startsWith(this.namespace)) {
localStorage.removeItem(key);
}
});
}
getAll() {
const items = {};
const keys = Object.keys(localStorage);
keys.forEach(key => {
if (key.startsWith(this.namespace)) {
const itemKey = key.replace(this.namespace, '');
items[itemKey] = JSON.parse(localStorage.getItem(key));
}
});
return items;
}
}
const userStorage = new NamespacedStorage('user');
userStorage.set('name', 'John');
userStorage.set('email', '[email protected]');
console.log('All user data:', userStorage.getAll());
// Method 4: Storage with encryption (simple)
class EncryptedStorage {
constructor(secret) {
this.secret = secret;
}
encrypt(text) {
// Simple XOR encryption (not secure, for demo only)
let result = '';
for (let i = 0; i < text.length; i++) {
result += String.fromCharCode(text.charCodeAt(i) ^ this.secret.charCodeAt(i % this.secret.length));
}
return btoa(result); // Base64 encode
}
decrypt(encrypted) {
const text = atob(encrypted);
let result = '';
for (let i = 0; i < text.length; i++) {
result += String.fromCharCode(text.charCodeAt(i) ^ this.secret.charCodeAt(i % this.secret.length));
}
return result;
}
set(key, value) {
const encrypted = this.encrypt(JSON.stringify(value));
localStorage.setItem(key, encrypted);
}
get(key, defaultValue = null) {
const encrypted = localStorage.getItem(key);
if (!encrypted) return defaultValue;
try {
return JSON.parse(this.decrypt(encrypted));
} catch (e) {
return defaultValue;
}
}
}
const secureStorage = new EncryptedStorage('mySecretKey');
secureStorage.set('password', 'secret123');
console.log('Password:', secureStorage.get('password'));Output
Name: John
Has name: true
Keys: ["name"]
Token: abc123
All user data: { name: 'John', email: '[email protected]' }
Password: secret123Understanding Storage Utilities
Storage utilities simplify common operations.
Utility Classes
•Encapsulate storage logic
•Handle errors
•Provide defaults
•Add features
Features
•Expiration
•Namespacing
•Encryption
•Helpers
Use Cases
•App configuration
•User preferences
•Cached data
•Session management
Best Practices
•Use classes for organization
•Handle errors gracefully
•Provide defaults
•Add useful features
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.