Storage Utilities in JavaScript
Utility functions for storage operations
IntermediateLocalStorage/SessionStorageExample 6 of 10
storage-utilities.js
1// Method 1: Storage helper class2class StorageUtil {3 constructor(storage = localStorage) {4 this.storage = storage;5 }67 set(key, value) {8 try {9 this.storage.setItem(key, JSON.stringify(value));10 return true;11 } catch (e) {12 console.error('Storage error:', e);13 return false;14 }15 }1617 get(key, defaultValue = null) {18 try {19 const item = this.storage.getItem(key);20 return item ? JSON.parse(item) : defaultValue;21 } catch (e) {22 console.error('Parse error:', e);23 return defaultValue;24 }25 }2627 remove(key) {28 this.storage.removeItem(key);29 }3031 clear() {32 this.storage.clear();33 }3435 has(key) {36 return this.storage.getItem(key) !== null;37 }3839 keys() {40 return Object.keys(this.storage);41 }4243 size() {44 let total = 0;45 for (let key in this.storage) {46 if (this.storage.hasOwnProperty(key)) {47 total += this.storage[key].length + key.length;48 }49 }50 return total;51 }52}5354const storage = new StorageUtil();55storage.set('name', 'John');56console.log('Name:', storage.get('name'));57console.log('Has name:', storage.has('name'));58console.log('Keys:', storage.keys());5960// Method 2: Storage with expiration61class ExpiringStorage {62 set(key, value, ttl) {63 const item = {64 value: value,65 expiry: Date.now() + ttl66 };67 localStorage.setItem(key, JSON.stringify(item));68 }6970 get(key) {71 const itemStr = localStorage.getItem(key);72 if (!itemStr) return null;7374 const item = JSON.parse(itemStr);75 if (Date.now() > item.expiry) {76 localStorage.removeItem(key);77 return null;78 }7980 return item.value;81 }8283 clearExpired() {84 const now = Date.now();85 for (let i = localStorage.length - 1; i >= 0; i--) {86 const key = localStorage.key(i);87 const itemStr = localStorage.getItem(key);88 try {89 const item = JSON.parse(itemStr);90 if (item.expiry && now > item.expiry) {91 localStorage.removeItem(key);92 }93 } catch (e) {94 // Not an expiring item, skip95 }96 }97 }98}99100const expiringStorage = new ExpiringStorage();101expiringStorage.set('token', 'abc123', 3600000); // 1 hour102console.log('Token:', expiringStorage.get('token'));103104// Method 3: Namespaced storage105class NamespacedStorage {106 constructor(namespace) {107 this.namespace = namespace + ':';108 }109110 set(key, value) {111 localStorage.setItem(this.namespace + key, JSON.stringify(value));112 }113114 get(key, defaultValue = null) {115 const item = localStorage.getItem(this.namespace + key);116 return item ? JSON.parse(item) : defaultValue;117 }118119 remove(key) {120 localStorage.removeItem(this.namespace + key);121 }122123 clear() {124 const keys = Object.keys(localStorage);125 keys.forEach(key => {126 if (key.startsWith(this.namespace)) {127 localStorage.removeItem(key);128 }129 });130 }131132 getAll() {133 const items = {};134 const keys = Object.keys(localStorage);135 keys.forEach(key => {136 if (key.startsWith(this.namespace)) {137 const itemKey = key.replace(this.namespace, '');138 items[itemKey] = JSON.parse(localStorage.getItem(key));139 }140 });141 return items;142 }143}144145const userStorage = new NamespacedStorage('user');146userStorage.set('name', 'John');147userStorage.set('email', 'john@example.com');148console.log('All user data:', userStorage.getAll());149150// Method 4: Storage with encryption (simple)151class EncryptedStorage {152 constructor(secret) {153 this.secret = secret;154 }155156 encrypt(text) {157 // Simple XOR encryption (not secure, for demo only)158 let result = '';159 for (let i = 0; i < text.length; i++) {160 result += String.fromCharCode(text.charCodeAt(i) ^ this.secret.charCodeAt(i % this.secret.length));161 }162 return btoa(result); // Base64 encode163 }164165 decrypt(encrypted) {166 const text = atob(encrypted);167 let result = '';168 for (let i = 0; i < text.length; i++) {169 result += String.fromCharCode(text.charCodeAt(i) ^ this.secret.charCodeAt(i % this.secret.length));170 }171 return result;172 }173174 set(key, value) {175 const encrypted = this.encrypt(JSON.stringify(value));176 localStorage.setItem(key, encrypted);177 }178179 get(key, defaultValue = null) {180 const encrypted = localStorage.getItem(key);181 if (!encrypted) return defaultValue;182 try {183 return JSON.parse(this.decrypt(encrypted));184 } catch (e) {185 return defaultValue;186 }187 }188}189190const secureStorage = new EncryptedStorage('mySecretKey');191secureStorage.set('password', 'secret123');192console.log('Password:', secureStorage.get('password'));
Output
Name: John
Has name: true
Keys: ["name"]
Token: abc123
All user data: { name: 'John', email: 'john@example.com' }
Password: secret123What's going on
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