Skip to content

Commit 2773937

Browse files
authored
Create CacheStoreWithTTL.cpp
1 parent 414c7a6 commit 2773937

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

CacheStoreWithTTL.cpp

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int getCurrentTimeStamp(){
5+
return 0; //assume this is a system function that returns the current timestamp
6+
}
7+
8+
//Implement a CacheStore that can store key values with some TTL info as well
9+
template <typename K, typename V>
10+
class CacheStore
11+
{
12+
//mapping key to value as well as a timestamp till its valid
13+
unordered_map<K, pair<V, int>> _mep;
14+
public:
15+
void Add(K key, V value, int ttl) {
16+
if(_mep.find(key) == _mep.end()) {
17+
int expirationTime = getCurrentTimeStamp() + ttl;
18+
_mep[key] = {value, expirationTime};
19+
}
20+
else {
21+
//depends on business logic how to handle this case
22+
//one approach is we can overwrite the value
23+
}
24+
}
25+
26+
//returns true if key existed and also alive
27+
bool Get(K key, V* out) {
28+
int currentTime = getCurrentTimeStamp();
29+
if(_mep.find(key) == _mep.end()) {
30+
out = NULL;
31+
return 0;
32+
}
33+
else {
34+
pair<V, int> cur = _mep[key];
35+
if (cur.second < currentTime) {
36+
//expired
37+
out = NULL;
38+
return 0;
39+
}
40+
else {
41+
*out = cur.first;
42+
return 1;
43+
}
44+
}
45+
}
46+
};
47+
48+
int main() {
49+
CacheStore<string, int> M;
50+
M.Add("rachit", 1, 10);
51+
M.Add("Uber", 2, 100);
52+
int* res = new int;
53+
if(M.Get("rachit", res)) cout << *res << endl;
54+
if(M.Get("Uber", res)) cout << *res << endl;
55+
56+
return 0;
57+
}

0 commit comments

Comments
 (0)