Storage Utilities
Utility functions for storage operations
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', 'john@example.com');
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'));Name: John
Has name: true
Keys: ["name"]
Token: abc123
All user data: { name: 'John', email: 'john@example.com' }
Password: secret123Understanding Storage Utilities
Storage utilities simplify common operations.
Utility Classes
Features
Use Cases
Best Practices
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.
Practical Learning Notes for Storage Utilities
This JavaScript program is part of the "LocalStorage/SessionStorage" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.
A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.
For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.