Created
April 30, 2019 16:37
-
-
Save gs-ysingh/7ccd27f5f461221fd64006f4a6f51c31 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Cache(maxSize) { | |
this.data = []; | |
this.maxSize = maxSize; | |
this.size = 0; | |
this.put = function(key, value, ttl) { | |
if(value.length > this.maxSize) { | |
throw new Error('string is too large'); | |
} | |
if(this.size + value.length > this.maxSize) { | |
this.lruEvict(); | |
} | |
var data = {}; | |
data.key = key; | |
data.value = value; | |
data.ttl = setTimeout(() => { | |
this.remove(key); | |
}, ttl); | |
this.remove(); | |
this.data.push(data); | |
this.size += value.length; | |
} | |
this.remove = function(key) { | |
var index = this.data.findIndex((item) => { | |
return item.key === key; | |
}); | |
if(index !== -1) { | |
clearTimeout(this.data[index].ttl); | |
this.data[index].ttl = null; | |
this.size -= this.data[index].value.length; | |
this.data.splice(index, 1); | |
} | |
} | |
this.lruEvict = function() { | |
var lastItem = this.data.splice(0, 1); | |
this.size = this.size - lastItem[0].value.length; | |
} | |
this.get = function(key) { | |
var index = this.data.findIndex((item) => { | |
return item.key === key; | |
}); | |
if(index === -1) { | |
throw new Error('Key is not present in cache'); | |
} else { | |
var item = this.data.splice(index, 1); | |
this.data.push(item[0]); | |
} | |
return item[0].value; | |
} | |
} | |
var obj = new Cache(100); | |
obj.put('a', 'lorem ipsum dolor sit amet', 10000); | |
obj.put('b', 'lorem ipsum dolor sit amet', 10000); | |
obj.put('c', 'lorem ipsum dolor sit amet', 10000); | |
obj.put('d', 'lorem ipsum dolor sit amet', 10000); | |
obj.get('b'); | |
obj.get('c'); | |
obj.get('d'); | |
// this will not be available | |
obj.get('a'); | |
//After 10 sec, this will not be available | |
obj.get('c'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment