Skip to content

Instantly share code, notes, and snippets.

@Kaptard
Created June 24, 2017 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kaptard/7f9a1ddf66f66159eff06e0a65958ba6 to your computer and use it in GitHub Desktop.
Save Kaptard/7f9a1ddf66f66159eff06e0a65958ba6 to your computer and use it in GitHub Desktop.
/**
* 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