ResultsCache

CSS

body {
    font: 14px/1.4em Helvetica, Arial;
    padding: 10px;
}

JavaScript

// Utility function to display log output
function logOutput(output) {
    $('body').append("<b>&gt</b> " + output + "<br />");
}

/**
 * ResultsCache definition
 */
var ResultsCache = function(computationFunction, cacheKeyGenerator) {
    this._cache = {};
    this._computationFunction = computationFunction;
    if (cacheKeyGenerator)
        this._cacheKeyGenerator = cacheKeyGenerator;
};

ResultsCache.prototype.compute = function() {
    // try to retrieve computation from cache

    var cacheKey = this._cacheKeyGenerator.apply(this, arguments);
    console.log("cache",this._cache);
    var promise = this._cache[cacheKey];
	
    // if not yet cached: start computation and store promise in cache 
    if (!promise) {
        var deferred = $.Deferred();
        promise = deferred.promise();
        this._cache[cacheKey] = promise;

        // perform the computation
        var args = Array.prototype.slice.call(arguments);
     
        args.push(deferred.resolve);
        
        this._computationFunction.apply(null, args);
    }

    return promise;
};

// Default cache key generator (works with Booleans, Strings, Numbers and Dates)
// You will need to create your own key generator if you work with Arrays etc.
ResultsCache.prototype._cacheKeyGenerator = function(args) {
    return Array.prototype.slice.call(arguments).join("|");
};






// Example: perform and cache ajax calls
var ajaxCache = new ResultsCache(function(id, resultHandler) {
    logOutput("Performing Ajax request for id '" + id + "'");
    $.getJSON('http://jsfiddle.net/echo/jsonp/?callback=?', {value: id}, function(data) {
        resultHandler(data.value);
    });
});

ajaxCache.compute(1).then(function(result) {
    logOutput("result: " + result);
});

ajaxCache.compute(2).then(function(result) {
    logOutput("result: " + result);
});

ajaxCache.compute(1).then(function(result) {
    logOutput("result: " + result);
});