2622. Cache With Time Limit

Implementing a Time-Limited Cache in JavaScript

In the world of web development, managing cache effectively can significantly improve the performance of your applications. Recently, I worked on a simple yet powerful Time-Limited Cache in JavaScript, which allows you to store key-value pairs that automatically expire after a specified duration. Let's dive into the implementation and explore how it works!

What is a Time-Limited Cache?

A time-limited cache is a data structure that stores items for a specific period of time. After this time elapses, the items are automatically removed from the cache. This is particularly useful for scenarios where you need temporary storage and want to ensure that stale data doesn't persist.

Key Features

  1. Dynamic Expiry: Each cache entry can have its own expiry time.

  2. Automatic Cleanup: Entries are automatically removed after their duration.

  3. Efficient Management: Utilizes JavaScript's Map and setTimeout for efficient data handling.

The Implementation

Here's a step-by-step breakdown of the TimeLimitedCache class implementation:

  1. Constructor: Initializes the cache using a Map.

  2. set Method: Adds or updates an entry with a specified duration.

  3. get Method: Retrieves the value associated with a key.

  4. count Method: Returns the number of active entries in the cache.

Code :

var TimeLimitedCache = function() { //constucter
    this.myCache = new Map();
};

TimeLimitedCache.prototype.set = function(key, value, duration) {
    //create a value to check data exist or not
    const hasData = this.myCache.get(key);
    //check by if statement
    if(hasData) {
        clearTimeout(hasData.timeLimit);
    }
    //set the value for certaion time
    const timeLimit = setTimeout(() => {
        this.myCache.delete(key);
    }, duration);
    //set the value
    this.myCache.set(key, {value, timeLimit});
    return Boolean(hasData);
};
TimeLimitedCache.prototype.get = function(key) {
    //geting the value using the Map has() method
    return this.myCache.has(key) ? this.myCache.get(key).value
 : -1
 };

TimeLimitedCache.prototype.count = function() {
    // returning the length
    return this.myCache.size;
};


 

Usage Example

To illustrate how to use the TimeLimitedCache, let's consider a simple example:

javascript
const timeLimitedCache = new TimeLimitedCache();
console.log(timeLimitedCache.set(1, 42, 1000)); // Output: false (new entry)
console.log(timeLimitedCache.get(1)); // Output: 42 (retrieved value)
console.log(timeLimitedCache.count()); // Output: 1 (one entry in the cache)
setTimeout(() => {
    console.log(timeLimitedCache.get(1)); // Output: -1 (entry expired)
    console.log(timeLimitedCache.count()); // Output: 0 (no active entries)
}, 1100);
    console.log(timeLimitedCache.get(1)); // Output: -1 (entry expired)
    console.log(timeLimitedCache.count()); // Output: 0 (no active entries)
}, 1100);

In this example:

  • We set a key-value pair with a 1-second expiry.

  • Retrieve the value before it expires.

  • After 1.1 seconds, the entry expires, and the cache is empty.

Conclusion

Implementing a time-limited cache in JavaScript is a great way to manage temporary data efficiently. This TimeLimitedCache class provides a simple yet powerful tool to handle dynamic expiry and automatic cleanup, ensuring your applications remain performant and responsive.

I hope you find this implementation useful. Feel free to share your thoughts and enhancements!

Comments

Popular posts from this blog

3Sum Closest: O(n²) Two-Pointer Magic šŸš€ leetcode: 16

Kadane's Algorithm: Maximum Subarray Problem - LeetCode(53) Solution

LeetCode Problem: Implement pow(x, n) leetcode:- 50