Functional Programming in Javascript

August 31st, 2009 by James Carr

Just a random, late night scribble for the boys and girls out there starting fresh with javascript and not understanding the power that you can harness with it. I’ve given this demonstration before, but it’s always fun to post because someone might learn something new. ;)

Anyway, you might be familiar with your usual function definition, let’s say a function that sums 2 numbers:

function sum(a,b){
  return a+b;
}

sum(2,5); // returns 7

That’s fine and dandy… but now let’s change this around a bit to better illustrate what a function is:

var pre = function(a,b){
  return a+b;
}

sum(2,5); // returns 7

Yep, that’s right… a function is just an object in javascript and the name of it is simply a variable. Now let’s make this a bit more interesting by creating a function that returns a running sum:

function runningSum(start){
  var sum = start;
  return function(a){
    return sum+=a;
  }
}
var sum = runningSum(3);
sum(2); // returns 5
sum(10); // returns 15

As you see, you can have a function return another function in javascript, and that function inherits the scope of the function that created it… in fact we could remove the temporary sum variable and get the same results:

function runningSum(start){
  return function(a){
    return start+=a;
  }
}
var sum = runningSum(3);
sum(2); // returns 5
sum(10); // returns 15

now, lets introduce the arguments variable, which gives you access to an array of agu ments passed into the function. A revised sum function:

function sum(){
  var sum = 0;
  for(var i = 0; i < arguments.length; i++){
    sum += arguments[i];
  }
  return sum;
}
sum(1,2,2,1); // returns six

The arguments object is a pretty damn cool object, if you want to look further, take a gander at the Mozilla documentation. Using the callee attribute of arguments (which returns the function instance itself), we can do something wicked:

var sum = 0;
function add(a){
  sum+=a;
  return arguments.callee;
}
add(1)(2)(3);
alert(sum); // displays 6

I find this can come in pretty handy when you need an accumulator of some sort… try it, it works! :)

Also, you can assign the scope of this while using functions, which can be useful if, for example, you want to call a function where this might resolve to the local scope (think ajax callbacks):

function greeting(){
  return "Hello " + this.name;
}

var person = {'name':'James'};
greeting.call(person); // returns "Hello James"

I also prefer to avoid polluting the global scope if I want a script that does something procedural when it’s included, in that case I just create a function and execute it on the spot:

(function(){
  var bleh = 3;
  alert(bleh+5); // alerts 8
})();
alert(bleh); // Reference Error: bleh is not defined

Finally, there’s a handy map function on arrays. It’s available in Mozilla, but not IE (afaik), however it is also available in jquery, so you can give it a try there.

[1,2,3,4,5].map(function(a){return a*a;}); // returns [1,4,9,16,25]

Overall, pretty basic stuff, but a nice refresher if you are unfamiliar. ;)

TDD Javascript With berilos.de JsUnit

June 26th, 2009 by James Carr

Evaluating this framework brings back memories… the year was 2005, I had been working for a small IT firm as one of the first developers hired, which as of 2005 included three developers. I had zero process in place and had never had any experience elsewhere as this was my first job. Somehow, from reading Royce’s Software Project Management to a book on RUP to a book on Scrum, I finally found my way to Extreme Programming and was trying my best to implement it. I had just picked up unit testing and was using SimpleTest (after trying PHPUnit out and deciding I liked SimpleTest better) and felt that I should be Test Driving all code, javascript included. So I joined #javascript on efnet and asked “Hey, what should I use? I’ve been trying jsUnit out…”

The reply I got was that I should stop using jsUnit from jsunit.net and start using the one on berlios.de instead as it was a more faithful port of JUnit, was more Object Oriented, and it was possible to run the tests from Rhino (which led me to asking what rhino is, and then a 2 hour longer conversation ensued).

Anyway, jsunit is just that… it’s a faithful port of JUnit 3.8.1 and is designed in a more object oriented way than it’s counterpart. In fact, the syntax looks similar to the current built in test runner in js-test-driver. With that out of the way, let’s take a quick look at the dirty details.

Read More »

Javascript Test Driven Development With YUI Test

June 18th, 2009 by James Carr

Tonight I’ve decided to bounce back and try out another testing framework that’s been on my list for awhile, YUI Test. From the site:

YUI Test is a testing framework for browser-based JavaScript solutions. Using YUI Test, you can easily add unit testing to your JavaScript solutions. While not a direct port from any specific xUnit framework, YUI Test does derive some characteristics from nUnit and JUnit.

Fair enough… lets look at the dirty details and then get started.

Read More »

More Test Driven Development With Javascript: JsTestDriver

June 16th, 2009 by James Carr

Just got back from the gym and it’s time for yet another evening of experimenting with test driven development in javascript. I’ve been hearing a lot about JsTestDriver lately, so tonight I’m going to see what all the fuss is about. :)

Read More »

Testdriving Javascript With jqUnit

June 15th, 2009 by James Carr

Whew… looks like my “Week of javascript TDD frameworks will really turn into a month of ‘em. Fine by me though, I like options. For a bit of randomness, I’m going to try out jqUnit. jqUnit is a TDD framework that takes quite a different approach… it is structured much like jquery is and tests are laid out in a jquery kind of way. Although it depends on jquery to run, your SUT does not have to have jquery as a dependency. Anyhow, let’s take a quick dive into the dirty details and then get started. :)

The Dirty Details

Basically another xUnit framework, but the syntax is radically different from any framework I’ve seen, xUnit or BDD. instead of your usual “assertXXXX” or spec syntaxes, it simply uses yep and okay . Most importantly, this is the framework used by jQuery to test itself.

Read More »

Yet Another Day of Test Driven Javascript: Screw.Unit

June 12th, 2009 by James Carr

First let me apologize for the delay in my posting. My intention was to post about a javascript testing framework each day, but the last couple of days I got a little stuck trying to get inspec to run.That coupled with the other things in life that compress my time I was just unable to make any progress! I finally decided to give up on inspec as it’s kind of specific to a certain domain (ServerJS) while my experiments have been rooted in the test driving of client side behavior. So, to move on, I’m going to do todays example using Screw.Unit!
Read More »

Test Driven Javascript: Using JSSpec

June 5th, 2009 by James Carr

For the first installment of my Week of TDD and BDD Javascript Frameworks I’m going to cover JSSpec. First I’ll cover some of the specifics and then jump straight into a demo of using it.

The Dirty Details

JSSpec, as the name implies, is a Behavior Driven Development framework based on the popular rspec ruby framework… as such it borrows heavily from rspec’s structure and functionality, using a function named “describe” to start a spec and values are evaluated by passing them to a function named value_of which returns an object containing methods for performing assertions on the value. For example:

  value_of([1,2,3]).should_contain(2);
  value_of(name).should_be("James);

Now for the other details:
Read More »

jquery-text-tools: Link urls with jQuery

April 12th, 2009 by James Carr

Here’s a little something I threw together today that is simple, yet a bit useful too. I’ve been working on an application that consumes text from a JSON service on the client side and populates the page with the results, in real time. Some of the snippets of text have links in them, so I wanted something quick and easy to “linkify” any urls that are contained within the text. The result is this:

var linkifiedHtml = $.link("Go to http://www.google.com to search");

Which simply puts an anchor around the contained url. You can also use CSS selectors too… say you want to linkify every paragraph with the class foo:

$('p.foo').link();

That pretty much sums it up. Go grab it off github and feel free to fork it/add to it.

Adding New Methods To Existing Javascript Objects

April 11th, 2008 by James Carr

Taking a lunch break from training today and I thought it’d be good to illustrate something that’s pretty standard in javascript, but might be pretty new for some. One of my favorite features is the ability to add new methods to existing object prototypes. For example, wouldn’t it be neat to be able to have an array method that sums all of the elements in the array?

The normal approach might be something like the following:

function sum(collection){
  var result = 0;
  for(var i = 0; i < collection.length; i++){
     result+= collection[i];
  }
  return result;
}
var a = [1,2,3,4];
alert(sum(a));

This would show an alert box with the value 10. Pretty simple. But what if we could do this?

alert([1,2,3,4].sum());

The answer… you can. All you need to do is add the sum method to the prototype of Array, which will make any new instance of array have the new method:

Array.prototype.sum = function(){
  var result = 0;
  for(var i = 0; i < this.length; i++){
     result+= this[i];
  }
  return result;
}

That does it. But what if we only want one array, not all arrays, to have a sum method? you can still do this by adding it to the actual object (this is where prototypes come into play):

var a = [1,2,3,4];
a.sum = function(){
  var result = 0;
  for(var i = 0; i < this.length; i++){
     result+= this[i];
  }
  return result;
}

alert(a.sum()); // prints 10
alert([1,2,3,4].sum()); // runtime error... object does not support this property

Hope that provides a good illustration of how to add new methods to existing object prototypes in javascript, as well as illustrate the distinction between objects and object prototypes. As an exercise for the reader, make the preceding examples work even if the collection contains non-numeric items. ;)

NFJS Coming Up (Yet Again)

March 2nd, 2008 by James Carr

Only a mere five days from now I’ll be attending the NFJS Gateway Software Symposium for the 4th time… and I’m pleased to say I’m quite excited. NFJS is one of those conferences that just has a knack for being fun, small, easily accessible, and very very educating.

The “educating” part however is the only aspect that has me a little worried, since this being my 4th NFJS conference I worry there may not be much new to see… and a quick initial glance at the sessions I easily spot many of the usual sessions they’ve had in the past… so what to do? ;)

Without a doubt, I’ll have to attend Michael Nygard’s session “Failures Come In Flavors.” I actually had the pleasure of meeting Michael last year at the GSS Fall edition at the hotel lobby bar… from the discussion we had about software development I could tell the session would be interesting, but unfortunately missed it due to having to head back to Columbia early on Sunday. So I’ll be “making it up” this time around. Additionally, he is also giving another session titled The 90 Minute Startup that sounds pretty interesting too.

The session that stands out is Nathaniel Schutta’s Designing for Ajax (Part 2). Why am I only interested in part 2? One reason… one reason only… Google Gears. Google Gears is one of the most interesting things I’ve toyed with lately that sadly your average developer has no idea what it is (but should).

Anyway, feel free to hit me up if you happen to be attending. If not, keep an eye here as I’ll try to post some fresh content daily from the sessions, if not just quick notes on what’s going on. Hopefully I’ll have something enlightening to post! :)