Skip to content

Instantly share code, notes, and snippets.

@arian
Forked from ibolmo/Function.prototype.memoize.js
Created December 27, 2010 10:27
Show Gist options
  • Save arian/756030 to your computer and use it in GitHub Desktop.
Save arian/756030 to your computer and use it in GitHub Desktop.
// A memoize function to store function results of heavy functions
// http://jsfiddle.net/arian/UQsEA/1/
(function(slice){
Function.prototype.memoize = function(hashFn, bind){
var cache = {}, self = bind ? this.bind(bind) : this, hashFn = hashFn || JSON.stringify;
return function(){
return ((key = hashFn(slice.call(arguments))) in cache)
? cache[key]
: (cache[key] = self.apply(bind, arguments));
};
};
})(Array.prototype.slice);
var dotProduct = function(first, second){
var l = first.length, result = 0;
if (second.length != l) return;
while (l--) result += first[l] * second[l];
console.log('[' + first + '] · [' + second + '] = ' + result);
return result;
}
var dotProductFast = dotProduct.memoize();
// Calculate the this simple dot products
// since they will not change over time, we can use the memoized function
console.log('first result: ' + dotProductFast([1, 2, 3, 4], [2, 3, 4, 5]));
console.log('second result: ' + dotProductFast([1, 2, 3, 4], [2, 3, 4, 5]));
console.log('third result: ' + dotProductFast([9, 2, 3, 4], [2, 3, 4, 5]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment