I recently discovered this thing called Functional Javascript, which contains a number of quite sexy modifications to Javascript's base classes to add extra, more functional things. While I was browsing Oliver Steel's blog, I came across his Javascript memoizer.
The idea behind memoization is that you don't have to perform a complex computation over and over to access a value that stays the same. His example is the length of a given bezier, unchanging curve. Calculating the length is processor expensive, even tho the length is constant.
So, along the way, he describes a method of doing this by modifying an object method on the fly. Instead of simply defining it like so:
foo.bar = function(){ ... }
You would define it like:
foo.bar = function(){ ... }.memoize();
And that got me thinking, because for a while I had been looking for a way to "monitor" a function, so that every time it get's called, you can notified via a callback. Now, I didn't want to have to do this by including the callback info in the function, I wanted to be able to just decide, "Oh, I'd like to start monitoring this function", whenever I wanted.
So I started experimenting, inspired by Function.prototype.memoize, and I discovered something quite fascinating and curious about Javascript.
x = function(){ ... }.method();
is completely valid Javascript, but
function(){ ... }. method();
is not. Calling a function on a function literal will only work when assigning that function to a value. Now, I understand why this should be the case: function(){ ... } is "special", in quotes, because just doing
function(){ ... }
doesn't work, so you obviously can't call a method on that because it breaks before it even gets to the method. But then why does
(function(){ ... })
work without any problems? Curiouser and curiouser.
Anyway, I like to think that the method of calling methods on functions during assignment like that is quite an elegant solution to the problem of memoizing and call monitoring as you create these functions. I never would've thought to do something like that, and I wonder how many other people also thought of it. And how many other things in Javascript are there like this? Little quirks that have a certain elegance to them.
That makes me wonder what sort of sublime programming language we could design. I have the odd sense that it might be named after a red colored precious gem.. :P
(This method of memoization, btw, was only mentioned on Oliver Steele's blog, which is where I saw it. It was apparently created by
Keith Gaughan.)