Featured Post

PHP Design Pattern

Sorry, this is a private post meant only for Red Ventures Developers. If you are a developer, log in here: http://developers.redventures.com/wp-admin/

Read More

Memoization

Posted by Garrett | Posted in Public | Posted on 26-07-2011

0

I was recently cleaning up a snippet of JavaScript that did something like the following.

var run = function(){

	var links = document.getElementById('results').getElementsByTagName('a');

	// some more code dealing with the DOM
	// bla bla bla.....

	// test for host and make decision based off or it
	if (document.location.host === 'google.com') {
		//...
	} else if (document.location.host === 'bing.com') {
		//...
	} else if (document.location.host === 'yahoo.com') {
		//...
	}

};

window.addEventListener('load', run, false);
window.addEventListener('hashchange', run, false);

While this does get the job done, it’s a bit repetitive, especially when being invoked multiple times. Once the page loads, we know what the host is, why should our functions be forced to do branching logic on something we already know? We could clean this up a good deal if we could just remember what our decisions the first time our function was called. This is a concept known as memoization.

var run = (function(){

	var links = document.getElementById('results').getElementsByTagName('a');

	// some more code dealing with the DOM
	// bla bla bla.....

	// test for host and make decision based off or it
	if (document.location.host === 'google.com') {
		return function() {
			// ...
		};
	} else if (document.location.host === 'bing.com') {
		return function() {
			// ...
		};
	} else if (document.location.host === 'yahoo.com') {
		return function(){
			// ...
		};
	}

})();

window.addEventListener('load', run, false);
window.addEventListener('hashchange', run, false);

Since JavaScript is awesome, we can simply just return another function from our function into a variable when the page initially loads, and from there on out, we will only be invoking a function that cares about the context which we are in. This also forms a closure, so our function still has a reference to the links variable.

No more waiting precious milliseconds figuring out something we already know. Yay for smarter code!

Write a comment