Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @param {number} capacity
- */
- var LRUCache = function(capacity) {
- this.capacity = capacity
- this.order = []
- this.map = {}
- };
- /**
- * @param {number} key
- * @return {number}
- */
- LRUCache.prototype.get = function(key) {
- let existingItem = this.getItem(key)
- if (existingItem !== -1) {
- this.order.splice(this.order.indexOf(key), 1)
- this.order.push(key)
- }
- return existingItem
- };
- LRUCache.prototype.getItem = function(key) {
- if (this.map.hasOwnProperty(key)) {
- return this.map[key]
- } else {
- return -1
- }
- };
- /**
- * @param {number} key
- * @param {number} value
- * @return {void}
- */
- LRUCache.prototype.put = function(key, value) {
- if (this.getItem(key) === -1) {
- if (this.order.length === this.capacity) {
- let keyToRemove = this.order.shift()
- delete this.map[keyToRemove]
- }
- } else {
- this.order.splice(this.order.indexOf(key), 1)
- }
- this.order.push(key)
- this.map[key] = value
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement