Saturday, September 09, 2006

JavaScript Memoization and Dependencies

I've extended Oliver Steele's appealing implementation of memoization in JavaScript to use a different dependency mechanism which also works with complex variables such as arrays or hashes by introducing a dependencies callback that returns a string or other simple datatype.

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]
}
}

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 }})


Take a look here if you're not familiar with the concept of Memoization.

(Thanks to Stephan for mentioning Oliver's post.)

No comments: