Cache Function
by HYEONGJINKIM
JavaScript
function cache(func) {
var cache = {};
return function () {
var key = JSON.stringify(Array.prototype.slice.call(arguments));
if (cache.hasOwnProperty(key)) {
console.log('From cache...')
return cache[key];
} else {
console.log('Computing..')
return cache[key] = func.apply(this, arguments);
}
}
}
var square = function(num) { return num*num; };
var cachedFunction = cache(square);
//Computing..
console.log(cachedFunction(1));
//Computing..
console.log(cachedFunction(2));
//Computing..
console.log(cachedFunction(3));
//From cache...
console.log(cachedFunction(2));