Skip to content

Instantly share code, notes, and snippets.

@03difoha
Last active September 24, 2019 06:47
Show Gist options
  • Save 03difoha/e643a123a480aed7d0a5389dcc791f8b to your computer and use it in GitHub Desktop.
Save 03difoha/e643a123a480aed7d0a5389dcc791f8b to your computer and use it in GitHub Desktop.
var ds = {
totalCapacity: 1000,
usedCapacity: 0,
items: {},
updateCapacity: function(){
this.usedCapacity = Object.values(this.items).reduce((t, {weight}) => t + weight, 0)
},
getItem: function (key) {
return this.items[key] ? this.items[key] : -1
},
putItem: function (key, value, weight) {
while (this.usedCapacity + weight > this.totalCapacity) {
this.evictItem()
}
this.items[key] = {
value: value,
weight: weight,
lastAccess: new Date()
}
this.updateCapacity()
},
evictItem: function () {
let lowest = Number.POSITIVE_INFINITY
let toEvict = ''
for (let i in this.items) {
itm = this.items[i]
score = itm.weight / Math.log(new Date() - itm.lastAccess)
if (score < lowest) {
lowest = score
toEvict = i
}
}
this.updateCapacity()
delete this.items[toEvict]
}
}
// computational effiency of getItem is O(n) as the reduce method in updateCapacity runs a function on each item in the list.
// I made this decision based on keeping the code clean when managing the capacity. The alternative I considered was looping through all the
// items in the list to update capacity but this seemed like extra mental clutter despite probably being faster.
// computational effiency of putItem is O(n) as we have two (non nested) loops, meaning the number of iterations is
// roughly equal to the number of items we have stored
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment