Skip to content

Instantly share code, notes, and snippets.

@vmattos
Last active August 29, 2015 14:06
Show Gist options
  • Save vmattos/fc2dc9139c4daf1bbbe7 to your computer and use it in GitHub Desktop.
Save vmattos/fc2dc9139c4daf1bbbe7 to your computer and use it in GitHub Desktop.
Simple caching algorithm for javascript functions that can be optionally added as middleware
function sleep(seconds)
{
var e = new Date().getTime() + (seconds * 1000);
while (new Date().getTime() <= e) {}
}
var Obj = function() {
this.fn = function(arg) {
console.log('Long operation zzzz...');
sleep(8);
return arg;
}
}
Obj.prototype.cache = function() {
var self = this;
if(!this._cache) {
this._cache = {}
console.log('Creating cache!');
}
var orig = {
fn: this.fn
};
return {
fn: function() {
var arg = arguments[0];
if(self._cache[arg] !== undefined) {
console.log('From cache!');
return self._cache[arg];
} else {
self._cache[arg] = orig.fn.apply(self, arguments);
return self._cache[arg]
}
}
}
}
var obj = new Obj();
console.log(obj.cache().fn(1));
console.log(obj.cache().fn(1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment