JavaScript
localStorage Operations
Wrap localStorage with expiration time and JSON support.
By EZ4Code Team
storagelocal-storage
Code
const storage = {
set(key, value, expire) {
const data = { value, expire: expire ? Date.now() + expire : null };
localStorage.setItem(key, JSON.stringify(data));
},
get(key) {
const raw = localStorage.getItem(key);
if (!raw) return null;
const data = JSON.parse(raw);
if (data.expire && Date.now() > data.expire) {
localStorage.removeItem(key);
return null;
}
return data.value;
},
remove(key) { localStorage.removeItem(key); }
};Explanation
Adds an expiration mechanism to localStorage, automatically cleaning expired data.
More JavaScript Snippets
Array Map Filter Reduce
Chain map, filter, reduce, find, some, and every on arrays.
Array Deduplication
Deduplicate an array using Set.
Deep Clone
Deep clone objects, supporting common data types.
Debounce Function
Wait a period of time after an event triggers before executing; reset the timer if triggered again during the wait.
Throttle Function
Limit a function to execute at most once within a time interval.
Promise.all Concurrency Control
A Promise executor with concurrency limit.