-
-
Save arian/756030 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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