Function.prototype.memoize = function(options) {
var fn = this
var cache = []
return function() {
var dependencyFlags = options.dependencies.apply(this, arguments)
var cacheHit = cache && cache[0] == dependencyFlags
if (cacheHit) {
return cache[1]
}
cache = [dependencyFlags, fn.apply(this, arguments)]
return cache[1]
}
}
var fn = this
var cache = []
return function() {
var dependencyFlags = options.dependencies.apply(this, arguments)
var cacheHit = cache && cache[0] == dependencyFlags
if (cacheHit) {
return cache[1]
}
cache = [dependencyFlags, fn.apply(this, arguments)]
return cache[1]
}
}
Here is some code that shows how memoize() can be used to specify dependencies both on function arguments and global variables.
var sortOrder = 0;
getSortedModel = function(user) {
// ... some lenghty calculation
alert("Performing Lengthy Calculation for " + user)
return [1, 2, 3, 4]
}.memoize({ dependencies: function(user) { return user + ":" + sortOrder }})
getSortedModel = function(user) {
// ... some lenghty calculation
alert("Performing Lengthy Calculation for " + user)
return [1, 2, 3, 4]
}.memoize({ dependencies: function(user) { return user + ":" + sortOrder }})
Take a look here if you're not familiar with the concept of Memoization.
(Thanks to Stephan for mentioning Oliver's post.)
No comments:
Post a Comment