22. May 2009, 14:09, by Leo Büttiker

From the for loop to the generator in JavaScript

I recently spent some time writing JavaScript code and do reviews of JavaScript features. JavaScript has some nice language features that make it easy to write short and readable code. (On the other hand it is also quite easy to write horrible code with it.) In this article I try to show you how you can refactor your code to something more readable.

Ms Office 2007 Tutorials order downloadable adobe photoshop cs4 extended Get Oem Microsoft Mappoint Europe 2009 buy adobe dreamweaver cs4 for cheap Get cheap oem microsoft windows vista ultimate online buy adobe livecycle apex movie converter oem adobe photoshop cs4 for mac codes Cheap System Center 10 Oem need to auto populate signature fields adobe acrobat Download Adobe Creative Suite 4 Master Collection Software adobe photoshop cs3 Get discounted abbyy finereader 9 pro multilang adobe software for macintosh Cheap Windows Vista Laptop adobe reader software distribution free get cheap adobe creative suite 3 master collection for mac deleting a page with adobe acrobat Cheap Apple Service Diagnostic 3s123 Oem adobe photoshop cs2 upgrade Adobe Photoshop Elements 7 Best Pricing adobe software pdf Download low price abbyy finereader 8 pro multilang adobe premiere crashes music software Microsoft Word Invoice Template download adobe acrobat 7 reader Finale Printmusic 2011 For Mac adobe photoshop cs4 extended mac (macintosh) software purchasing Get cheap autodesk navisworks simulate 2010 adobe photo shop trick and tip best price adobe contribute cs5 adobe premiere cs4 vs final cut pro buy autocad architecture adobe premier cs5 vs sony vegas pro 9 best price cyberlink truetheater enhancer adobe premier pro 1.5 Windows Xp Update adobe photoshop cs4 v Purchase Adobe Acrobat 8.0 adobe video editing software trials Ashampoo music studio 3 adobe photoshop cs3 extended software wholesale Cost Of Microsoft Office 2003 buy cheapest adobe creative suite 4 master collection Purchase adobe illustrator cs4 adobe soundbooth cs5 mac Windows 7 Extras adobe software educational discount Microsoft word clipart buy adobe dreamweaver cs4 for cheap windows 7 ultimate 32 bit product full version buy adobe livecycle Coreldraw Graphics Suite X3 adobe photoshop cs4 for mac codes buy adobe professional need to auto populate signature fields adobe acrobat adobe photoshop cheapest price adobe photoshop cs3 buy adobe creative suite cs3 adobe software for macintosh Microsoft office 2003 access adobe reader software distribution free Buy genuine windows xp deleting a page with adobe acrobat Magix audio cleaning lab 15 deluxe oem adobe photoshop cs2 upgrade Corel Dvd Moviefactory 6 Plus adobe software pdf Download Oem Adobe Cs4 Master Collection Online adobe premiere crashes music software Microsoft gas prices download adobe acrobat 7 reader micosoft office 2010 adobe photoshop cs4 extended mac (macintosh) software purchasing Buy cheap adobe photoshop cs2 v 9.0 adobe photo shop trick and tip discounted student software adobe premiere cs4 vs final cut pro windows xp 3 adobe premier cs5 vs sony vegas pro 9 Ms office finder adobe premier pro 1.5 Order downloadable microsoft office 2007 professional adobe photoshop cs4 v Windows 7 ultimate n adobe video editing software trials autodesk mudbox price adobe photoshop cs3 extended software wholesale Windows Xp Sp3 Black Edition Cro Rat buy cheapest adobe creative suite 4 master collection Discount engineering software adobe soundbooth cs5 mac Get Low Price Oem Microsoft Windows Server 2008 Microsoft Sql Server 2008 Online adobe software educational discount Navicat for oracle for mac oem buy adobe dreamweaver cs4 for cheap Cheap Hot Studio Creative Inspirations Oem buy adobe livecycle Acrobat Pro Oem adobe photoshop cs4 for mac codes Download Low Price Oem Microsoft Windows Server 2008 Microsoft Sql Server 2008 need to auto populate signature fields adobe acrobat Adobe Cheap Photo Shop Software adobe photoshop cs3 busysync for mac adobe software for macintosh Best Price Autodesk 3d Studio Max 2011 Design adobe reader software distribution free Get Cheap Adobe Dreamweaver Cs3 deleting a page with adobe acrobat microsoft office 2000 trial adobe photoshop cs2 upgrade get cheap cakewalk sonar 8 producer edition online adobe software pdf Adobe photoshop elements 6 mac buy adobe premiere crashes music software Windows 7 family 3 pack download adobe acrobat 7 reader Were to buy adobe adobe photoshop cs4 extended mac (macintosh) software purchasing Download Microsoft Office 2000 adobe photo shop trick and tip Discounts On Adobe Photoshop adobe premiere cs4 vs final cut pro Ms Office Small Business 2000 adobe premier cs5 vs sony vegas pro 9 windows vista themes adobe premier pro 1.5 Office 2007 price in india adobe photoshop cs4 v Microsoft 2010 Office Best Price adobe video editing software trials Microsoft Oem Software Biz adobe photoshop cs3 extended software wholesale best price adobe premiere cs4 pro buy cheapest adobe creative suite 4 master collection Adobe fireworks cs4 adobe soundbooth cs5 mac Price ms office 2003 adobe software educational discount Get discounted adobe creative suite 3 master collection for mac buy adobe dreamweaver cs4 for cheap Ms office online retailers - best deals buy adobe livecycle Get Low Price Adobe Creative Suite 4 Design Premium For Mac adobe photoshop cs4 for mac codes intuit quicken home and business 2010 oem need to auto populate signature fields adobe acrobat student discount on microsoft office adobe photoshop cs3 Best price creative suite 5 web premium adobe software for macintosh audio edit magic oem adobe reader software distribution free Free microsoft office xp cd deleting a page with adobe acrobat Download Microsoft Office Home And Student 2007 adobe photoshop cs2 upgrade microsoft office 2010 full adobe software pdf windows 7 upgrade from vista adobe premiere crashes music software visio standard 2007 download adobe acrobat 7 reader Microsoft office 2010 standart (64-bit) adobe photoshop cs4 extended mac (macintosh) software purchasing buy microsoft office online adobe photo shop trick and tip Buy Microsoft Office 2007 Standart License adobe premiere cs4 vs final cut pro Buy office 2007 professional oem adobe premier cs5 vs sony vegas pro 9 Winzip pro 14 oem adobe premier pro 1.5 Windows server 2008 datacenter 32bit adobe photoshop cs4 v Student Version Adobe Photoshop Buy adobe video editing software trials What Is Microsoft Office adobe photoshop cs3 extended software wholesale cheap microsoft visio buy cheapest adobe creative suite 4 master collection bigasoft mp4 converter oem adobe soundbooth cs5 mac Buy cheap software adobe elearning suite adobe software educational discount purchase adobe photoshop for mac buy adobe dreamweaver cs4 for cheap purchase adobe illustrator buy adobe livecycle Buy Adobe Photoshop Online adobe photoshop cs4 for mac codes Buy autocad 2005 need to auto populate signature fields adobe acrobat Buy Cheap Imsi Designcad 3d Max 20 adobe photoshop cs3 Cheap photoshop cs adobe software for macintosh Get Discounted Oem Solidworks 2009 adobe reader software distribution free Buy Discount Windows 7 Ultimate 64 Bit deleting a page with adobe acrobat Lynda.com dreamweaver cs5 essential training oem adobe photoshop cs2 upgrade Windows Xp Tips adobe software pdf oem microsoft windows xp professional adobe premiere crashes music software order downloadable adobe creative suite 4 master collection download adobe acrobat 7 reader Adobe Production Suite Academic Price adobe photoshop cs4 extended mac (macintosh) software purchasing Where Can I Buy Microsoft Office Project Professional 2003 Sp3 adobe photo shop trick and tip Photoshop retailing price singgapore adobe premiere cs4 vs final cut pro Cheap sony vegas pro 9 64 bit oem adobe premier cs5 vs sony vegas pro 9 Cheap Adobe Software Download adobe premier pro 1.5 Purchase windows office adobe photoshop cs4 v Download low price rosetta stone version 3 arabic all levels set for mac adobe video editing software trials microsoft office outlook 2003 calendar recall adobe photoshop cs3 extended software wholesale Buy Photoshop 9 buy cheapest adobe creative suite 4 master collection Microsoft Office Versions adobe soundbooth cs5 mac cyberlink powerdirector 7 ultra adobe software educational discount Cheap adobe photo elements 5 upgrade buy adobe dreamweaver cs4 for cheap Microsoft office 2007 suite product s buy adobe livecycle Windows xp secrets adobe photoshop cs4 for mac codes buy cheap adobe indesign cs5 need to auto populate signature fields adobe acrobat Ms office for mac adobe photoshop cs3 download low price oem adobe cs4 production premium online adobe software for macintosh Usa Hosted Ms Office adobe reader software distribution free Buy Used Windows Xp Professional Sp2 64 Bit Inexpensive deleting a page with adobe acrobat Fontlab studio 5 for mac adobe photoshop cs2 upgrade Ms office training manuals adobe software pdf windows 7 theme download adobe premiere crashes music software buy cheap microsoft office visio professional 2007 sp2 software download adobe acrobat 7 reader Best price mathworks matlab 2010b adobe photoshop cs4 extended mac (macintosh) software purchasing Microsoft office 2003 professional (deutsch) with business contact manager adobe photo shop trick and tip Windows xp media center 2005 number adobe premiere cs4 vs final cut pro Microsoft Office Home And Student 2007 Cheap adobe premier cs5 vs sony vegas pro 9 Microsoft powerpoint buy adobe premier pro 1.5 Ms Office 7 adobe photoshop cs4 v Microsoft adobe adobe video editing software trials Microsoft Office Sbe adobe photoshop cs3 extended software wholesale adobe dreamweaver cs5 student and teacher edition buy cheapest adobe creative suite 4 master collection Windows 7 Price Upgrade adobe soundbooth cs5 mac Get discounted adobe creative suite 4 design premium for mac online adobe software educational discount nero multimedia suite 10 oem buy adobe dreamweaver cs4 for cheap Lynda.com encore cs5 essential training oem buy adobe livecycle Quick tips on using microsoft office frontpage adobe photoshop cs4 for mac codes Lynda.com illustrator cs5 new features need to auto populate signature fields adobe acrobat buy microsoft home and student download adobe photoshop cs3 Buy Cheap Contribute Cs5 adobe software for macintosh microsoft windows vista home basic with sp2 (64 bit) adobe reader software distribution free Cheap software download adobe deleting a page with adobe acrobat Purchase adobe creative suite adobe photoshop cs2 upgrade

We may start with this non-fictional example:

/**
* Returns array of uids of selected items
*/
getSelected:function() {
	var returnArray = new Array();
	var modelFriendListItems = this.modelFriendListItems.getSelected();

	for (var index = 0 ; index < modelFriendListItems.length ; ++index) {
		if(!modelFriendListItems[index].isFacebookUser)
			returnArray.push(modelFriendListItems[index].id);
	}

	return returnArray;
},

It’s just one function out of a class that does quite something typical. This function goes over a list of items (iterate) and builds an array out of some of this items (filter). A friend of mine does some ruby coding and in ruby this would look something like this:

this.modelFriendListItems.getSelected().select{|item| !item.isFacebookUser}.collect {|item| item[:id]}

This is quite short and still yet readable. In JavaScript you can go as well in the direction of more functional programming. So let us refactor the JavaScript example above over some iterations. The following examples use prototype.js because this framework extends the JavaScript array with some fancy functions.

First we replace the “new Array()” term with the shorter term ‘[]‘. Then we try to get rid of the for loop which is quite a easy place to create a bug. Prototype does extend each iterable object (array is one of them) with a set of functions. One of them is the “each” function which does apply the anonymous function given as a parameter to each element of the iterable.

/**
* Returns array of uids of selected items
*/
getSelectedFB:function() {
	var result = [];
	this.modelFriendListItems.getSelected().each(function(item) {
		if(item.isFacebookUser){ result.push(item.id);  }
	});
	return result;
},

This is in my point of view already easier to read and it might be harder to create bugs as in a for loop. I do not like that you have to define a result array ‘outside’ of the main function. So the following code will do exactly the same in a more recursive style. You give as a starting value a empty array to inject and the anonymous function does now have to parameter where the first one is the array with the values and the second one is again the current item. You have to return the array at the end of the function. This makes the code again a bit shorter.

getSelected:function() {
	return this.modelFriendListItems.getSelected().inject([], function(array,item) {
		if(!item.isFacebookUser){ array.push(item.id);  }
		return array;
	});
},

You get the code might get a bit more readable it you use two other functions of prototype. ‘findAll‘ does return a array of all items that do match the given filter function. ‘pluck‘ does return an array with the values of a given field from all items.

getSelected:function() {
	return this.modelFriendListItems.getSelected().findAll(funtion(item){
	return !item.isFacebookUser;}).pluck('id');
},

The only way, I can think of, to make this short and more readable would be to have the function ‘filterAllBy’ and ‘filterAllByNot’ in prototype. This is currently not the case, so the example bellow will not work.

getSelected:function() {
	return this.modelFriendListItems.getSelected().filterAllByNot('isFacebookUser').pluck('id');
},

Some people did ask me if this code is not slower. Well it is! During the iteration of refactoring you lose some speed, but that should usually not matter in a real world application. But I spend also some time on how you could make your code faster with smart functional programing. I found out that generators (the one from python) are quite a good way to save cpu time under some circumstances.

For this I made up this ridiculous example. It’s the same thats in the article about phyton in the german computer magazin c’t (“Neues aus der Schlangengrube”, c’t 5.2009, p. 198).

var squares = $R(1, 1000000).map(function(n) {
	return n * n;
});

var result = [];
squares.each(function(n) {
	if (n > 100) throw $break;
	result.push(n);
});

$("output").innerHTML += result;

Off course this example is horible slow and will nearly crash your browser. I measured something like 24 seconds on a IE 8, something around 6.5 seconds on a Firefox 3 and around 400 milliseconds on chrome. A lot of the numbers you generate into the array squares are never used. With a generator you only generate the numbers you actually need.

I actually implemented a generator for prototype.js. It’s quite easy to create a own enumerable in prototype you just have to extend enumberable and implement the ‘_each‘ method. I did this in the following example with the class Generator. I also did implement the method mapGen directly into the Enumerable, it does have the same function as prototype.

var Generator = Class.create();

[...]
 mapGen: function(iterator, context) {
		var result = new Generator(iterator, this);
		return result;
	},
[...]

Object.extend(Generator.prototype, Enumerable);
Object.extend(Generator.prototype, {

	initialize: function(generator, enumerable) {
		this.generator = generator;
		this.enumerable = enumerable;
	},

	_each: function(iterator) {
		this.enumerable.each(function(item){
			iterator(this.generator(item));
		}, this);

	},
});

The code looks afterwards still nearly the same:

var squares = $R(1, 1000000).mapGen(function(n) {
  return n * n;
});

var result = [];
squares.each(function(n) {
  if (n > 100) throw $break;
  result.push(n);
});

$("output").innerHTML += result;

The real difference is the execution time. As the first example took some seconds on the most browser, this code here runs in around 1 millisecond on all browsers. Nice looking code does not have to be slow, with some smart tricks you can write short, readable and fast code.

Filed under: PHP,Programming

3 Comments »

  1. Seems like a nice exercise, but for the real world project i would still recommend jquery.

    It really does all of that …. its ready, tested, compatible … plus you don’t have to write/research anything.

    ps. used to use prototype and its bit messy, lots of code and pollutes prototype. You cant stop loving jquery once you use it …. you just cant.

    nice any way, cheers

    Comment by Artur — 25. May 2009 @ 10:35

  2. Thanks for your comment Artur. I did not looked to deep into jquery, but it looks like a nice framework.
    What I like about prototype is that it is very decupled from the task you do, jquery is more coupled to the gui and in my point of view it is also sometimes a bit “magic”.

    Comment by leo — 27. May 2009 @ 17:49

  3. thank!! Great Post!!!

    Comment by FeedsTech.com — 13. July 2009 @ 09:00

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2013 tilllate Schweiz AG - Powered by WordPress