@se-oss/lru
v1.0.1
Published
A feature-rich LRU cache engineered for high performance, offering excellent throughput on par with industry-standard libraries.
Maintainers
Readme
@se-oss/lru
@se-oss/lru is a feature-rich LRU cache engineered for high performance, offering excellent throughput on par with industry-standard libraries. It is designed for modern applications that require efficient caching with advanced features like TTL, size-based eviction, and asynchronous fetching.
📦 Installation
npm install @se-oss/lrupnpm
pnpm install @se-oss/lruyarn
yarn add @se-oss/lru📖 Usage
Quick Example
@se-oss/lru is a powerful and easy-to-use LRU cache for Node.js and the browser. Here’s a quick example to get you started:
import { LRUCache } from '@se-oss/lru';
// Create a cache with a max of 100 items and a 5-minute TTL
const cache = new LRUCache<string, number>({
max: 100,
ttl: 1000 * 60 * 5, // 5 minutes
});
// Set some values
cache.set('key1', 123);
cache.set('key2', 456);
// Get a value
console.log(cache.get('key1')); // 123
// Check if a key exists
console.log(cache.has('key2')); // true
// Delete a key
cache.delete('key1');
console.log(cache.has('key1')); // false
// The cache will automatically evict the least recently used items
// and expire items based on the TTL.With TTL (Time-To-Live)
import { LRUCache } from '@se-oss/lru';
const cache = new LRUCache<string, string>({
max: 100,
ttl: 1000 * 60 * 5, // 5 minutes
});
cache.set('session', 'user-session-data');
// The item will automatically expire after 5 minutesAsynchronous Fetching
The fetch method allows you to transparently handle cache misses by fetching data from an external source.
import { LRUCache } from '@se-oss/lru';
const cache = new LRUCache<string, any>({
max: 100,
fetchMethod: async (key) => {
console.log(`Fetching ${key} from API...`);
const response = await fetch(`https://api.example.com/data/${key}`);
return response.json();
},
});
async function getData(key: string) {
const data = await cache.fetch(key);
console.log(data);
}
getData('user-profile'); // Fetches from API
getData('user-profile'); // Returns from cache📚 Documentation
For all configuration options, please see the API docs.
🤝 Contributing
Want to contribute? Awesome! To show your support is to star the project, or to raise issues on GitHub
Thanks again for your support, it is much appreciated! 🙏
License
MIT © Shahrad Elahi and contributors.
