Skip to content

Instantly share code, notes, and snippets.

@calebrash
Last active August 29, 2015 14:21
Show Gist options
  • Save calebrash/f8bc04d9099e4ddee224 to your computer and use it in GitHub Desktop.
Save calebrash/f8bc04d9099e4ddee224 to your computer and use it in GitHub Desktop.
JS cache decorator function
/**
* Cacheable decorator function.
* @returns cacheable function. Results will be cached based on first argument.
**/
let cacheable = function (f) {
var __ = {};
return function () {
if (__[arguments[0]]) {
return __[arguments[0]];
} else {
__[arguments[0]] = f.apply(null, arguments);
return __[arguments[0]];
}
};
};
// example 1: not cached
let fib = function (n) {
if (n === 0) {
return 0;
} else if (n === 1) {
return 1;
} else {
return fib(n-1) + fib(n-2);
}
};
// example 2: cached
let fib2 = cacheable(function (n) {
if (n === 0) {
return 0;
} else if (n === 1) {
return 1;
} else {
return fib2(n-1) + fib2(n-2);
}
});
// results, times using console.time('...');
var n = 45;
fib(n); // 15689.771ms
fib2(n); // 0.090ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment