Created
June 24, 2017 17:03
-
-
Save Kaptard/7f9a1ddf66f66159eff06e0a65958ba6 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
/** | |
* Cache to reduce traffic/disk usage from very active people | |
*/ | |
class Cache { | |
constructor() { | |
this.offers = [] | |
this.duration = 180000 // in ms | |
} | |
/** | |
* Find given object in cache | |
*/ | |
find(object) { | |
let found = null | |
let index = null | |
this.offers.forEach((offer, i) => { | |
if (offer.user === object.user && | |
offer.item === object.item && | |
offer.component === object.component && | |
!this.isExpired(offer)) | |
{ | |
found = offer | |
index = i | |
} | |
}) | |
if (found && index) { | |
return { | |
found: found, | |
index: index | |
} | |
} else { | |
return null | |
} | |
} | |
/** | |
* Add offer to cache if new | |
*/ | |
add(offer) { | |
let cacheData = { | |
user: offer.user, | |
item: offer.item, | |
component: offer.component, | |
createdAt: new Date | |
} | |
this.find(cacheData) ? null : this.offers.push(cacheData) | |
} | |
/** | |
* Remove cached object from this | |
*/ | |
remove(value) { | |
let index = null | |
if (typeof value === "number") { | |
index = value | |
} else { | |
index = this.find(value).index | |
} | |
this.offers = this.offers.splice(index, 1) | |
} | |
/** | |
* Check if cached object is expired | |
*/ | |
isExpired(offer) { | |
if (new Date - offer.createdAt > this.duration) { | |
this.remove(offer) | |
return true | |
} else { | |
return false | |
} | |
} | |
} | |
module.exports = new Cache |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment