Skip to content

Instantly share code, notes, and snippets.

@mstarkman
Created August 9, 2011 01:50
Show Gist options
  • Save mstarkman/1133259 to your computer and use it in GitHub Desktop.
Save mstarkman/1133259 to your computer and use it in GitHub Desktop.
JavaScript Masters Class - Exercise 7
function convertToArray(iterable) {
return Array.prototype.slice.call(iterable);
}
Function.prototype.cached = function() {
var __method = this;
// This is to ensure there is only one argument, otherwise just return the results of the calling method.
if (__method.length != 1)
{
console.log("Cannot cache this method (" + __method.name + ") because there is not exactly one argument");
return function() {
return __method.apply(this, convertToArray(arguments));
}
}
__method.cache = {};
return function() {
var argToProcess = arguments[0];
if (__method.cache[argToProcess] != null)
{
console.log("Cache hit argument: " + argToProcess);
return __method.cache[argToProcess];
}
console.log("Cache miss argument: " + argToProcess);
__method.cache[argToProcess] = __method.apply(this, [argToProcess])
return __method.cache[argToProcess];
}
}
var sin = Math.sin.cached();
var runTests = function() {
console.log(sin(1)); // Output - Cache miss argument: 1
console.log(sin(2)); // Output - Cache miss argument: 2
console.log(sin(1)); // Output - Cache hit argument: 1
console.log(sin(2)); // Output - Cache hit argument: 2
}
runTests();
// This will print -
var unCachableMethod = function unCachableFunc(a, b) {
console.log("This is a: " + a);
console.log("This is b: " + b);
}.cached(); // Output - Cannot cache this method (unCachableFunc) because there is not exactly one argument
unCachableMethod("paramA", "paramB");
// Output -
// This is a: paramA
// This is b: paramB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment