Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * @param {number} capacity
  3.  */
  4. var LRUCache = function(capacity) {
  5.     this.capacity = capacity
  6.     this.order = []
  7.     this.map = {}
  8. };
  9.  
  10. /**
  11.  * @param {number} key
  12.  * @return {number}
  13.  */
  14. LRUCache.prototype.get = function(key) {
  15.     let existingItem = this.getItem(key)
  16.     if (existingItem !== -1) {
  17.         this.order.splice(this.order.indexOf(key), 1)
  18.         this.order.push(key)
  19.     }
  20.     return existingItem
  21. };
  22.  
  23. LRUCache.prototype.getItem = function(key) {
  24.     if (this.map.hasOwnProperty(key)) {
  25.         return this.map[key]
  26.     } else {
  27.         return -1
  28.     }
  29. };
  30.  
  31. /**
  32.  * @param {number} key
  33.  * @param {number} value
  34.  * @return {void}
  35.  */
  36. LRUCache.prototype.put = function(key, value) {
  37.     if (this.getItem(key) === -1) {
  38.         if (this.order.length === this.capacity) {
  39.             let keyToRemove = this.order.shift()
  40.             delete this.map[keyToRemove]
  41.         }
  42.     } else {
  43.         this.order.splice(this.order.indexOf(key), 1)
  44.     }
  45.     this.order.push(key)
  46.     this.map[key] = value
  47. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement