Monthly Archives: March 2014

Underscore.js Avails Interesting Possibilities with Reduce

Since I began playing around with Underscore.js, I have become obsessed with its reduce method. reduce takes a collection (or an object) and returns a single value. But it is the way in which it does that which makes it compelling. From the documentation, its signature is:

_.reduce(list, iterator, memo, [context])

I’ll start out with a simple example. Probably the kind of example you’ll see everywhere around the Internet:

var result = _.reduce([100, 25, 2], function(memo, num) {
	 return memo / num;
});
// result === 2

The iterator function is being applied to each of the elements of the list. But not only that, it is making available to each iteration the result of the previous iterator-function’s result.

  • In the first iteration, memo has the value 100 and num is 25.
  • In the second iteration, memo has the value 4 and num is 2.

As you can see, the value of memo in the second iteration is equal to the result of the iterator function from the first iteration. So we have this concept of a value which is travelling through the iterations. The parameter memo is short for memoization. This is an implementation detail which is not relevant to this post. As that parameter travels from function to function through the iterations, I am using the name traveller for the purposes of this post.

There are only 2 iterations in this example because the list has 3 items and we have not passed it a seed value as the 3rd possible parameter. If we change that function to the following, we will get 3 iterations and the value of traveller on the 1st iteration will be 10000, whilst the value of num will be 100.

var result = _.reduce([100, 25, 2], function(traveller, num) {
	 return traveller / num;
}, 10000);
// result === 2

When it comes to the iterator function, you are free to be very creative in there. But first, I just want to point out that it is not limited to integers. The following example creates a sentence out of a string array:

var words = ['Reduce', 'is', 'an', 'interesting', 'method'];

var sentence = _.reduce(words, function(traveller, current) {
	var collate = traveller + ' ' + current;
	return collate;
});
//	sentence === 'Reduce is an interesting method'

You can also pass an object as the first parameter. This is where you can do some interesting stuff, like the following example that creates an address object from a person object:

var person = {
	name: 'Dave',
	age: 39,
	address: '28 Scenic Road',
	suburb: 'Kenmore',
	postcode: 4069
};

var address = _.reduce(person, function(traveller, objectValue, objectMember) {
    switch (objectMember) {
		case 'address':
		case 'suburb':
		case 'postcode':
			traveller[objectMember] = objectValue; break;
		default : break;
    }
    return traveller;
}, {});

You can see that I have passed an empty object as the 3rd parameter to reduce, which will be the initial value of the traveller parameter.

Note that I’m not saying the last example is the best way to achieve that end. But that example does show that you can use the reduce function for a great many things beyond simple arithmetic and sentence construction.

Perhaps in a month or 2 I’ll have a really good example that solves a problem nice and elegantly.

Until then!

Git Alias for Resetting Web.config

In circumstances where the only thing that changes in the Web.config file is the connectionstrings element (my local machine v.s my collaborators’ machines), I found myself entering the following command before every commit:

git reset HEAD TheNameOfTheWebProject/Web.config

Well, I got sick of typing all that, so I decided to create a simple alias.

git config alias.rew 'reset HEAD TheNameOfTheWebProject/Web.config'

Now my workflow looks like this:

git add -u
git rew
git commit -m "Some message about changes"

Note, I did not make the alias global, as it only applies to the Web.config of that particular project.

Caching Dom Objects with jQuery

UPDATE

The technique in this post is incorrect and does not work. I failed to realize that jQuery’s selector method (i.e. $() ) always returns a jQuery object. If the element is not in the dom, the jQuery object will be an empty set. But a set nonetheless and not null. Thus, it will never coalesce in the way I intended. I wondered why no-one else was doing this. It seems I have my answer.


I learnt something interesting about JavaScript that I was not aware of this last week. I’ll elaborate by walking you through what I discovered. Basically, I was trying to come up with a pattern that stored a jQuery object, and if for some reason that object had become null at some point, then a failsafe re-query would occur. It looked like this:

  1. Declare a variable
  2. Add it to the pageObjects object, with a cascade to the jQuery selection call
  3. Prime the variable in the document.ready function
  4. All dom manipulations are via the pageObjects object
var someDiv; // step 1

// step 2
var pageObjects = {
  someDivOnPage: someDiv || $('#someDiv'), // different name not necessary, but illustrative
  otherProperty: // ... pageObjects has many properties 
};

//********* document.ready function ********* / 
$(function() {
    // step 3
    someDiv = $('#someDiv');
});

//  ... access object later in script ...
// step 4
pageObjects.someDivOnPage.css('color', #eeeeee);

I discovered, after a while, that this did not work. If that div in one operation was removed from the dom, and re-added in another operation, calling pageObjects.someDivOnPage was undefined. Apparently, the coalesce in that statement was a one-off. That is, the first time pageObjects.someDivOnPage is accessed, the statement coalesces to the jQuery query as planned. But that statement only runs once and the property of that object is stored in a memory location. Once the element underpinning that jQuery object is removed from the dom, that property no longer points to that jQuery object and it doesn’t coalesce to the re-query as it did upon first access.

The proper way to do it is as follows:

var someDiv;

var pageObjects = {
  someDivOnPage: function () {
	return someDiv || $('#someDiv'); // different name not necessary, but illustrative
  },
  otherProperty: // ... pageObjects has many properties 
};

//********* document.ready function ********* / 
$(function() {
    someDiv = $('#someDiv');
});

//  ... access object later in script ...
pageObjects.someDivOnPage().css('color', #eeeeee);

As you can see, I have changed the property in the pageObjects object to be a function. And later on, when I reference that property I call it as a function.

So, the conclusion is that when the interpreter first parses the pageObjects object, the properties are assigned in the way that an expression is executed. To use pseudo code, it would look like this:

// for my first flawed approach.
... {
  someDivOnPage = someDiv || $('#someDiv');
};

// for my corrected approach
... {
  someDivOnPage = function () {
	return someDiv || $('#someDiv'); // different name not necessary, but illustrative
  };
};

That assignment occurs once and the result of that expression is assigned to the property. Makes complete sense really. It’s just something I had not picked up on. Felt like a goose.

So you’re probably wondering about performance? Well, that was the whole idea. The project which I am working on had jQuery performing queries heaps of times for the same dom objects in different operations during the lifecycle of the page (button-clicks, mouse-overs etc.).

If you look at this benchmark which I created at jsperf.com, you will see that this approach is very performant.

The other advantage is that if you are using a good IDE, you get intellisense when you “dot through” to the relevant property on the pageObjects object. This makes maintenance a lot easier and reduces the opportunity for typos when writing out each and every jQuery selector.

A Branching Strategy Using Git

An index of the HomeLibrary application posts can be found here.

Up until now, I have been performing commits against the master branch (and pushing to origin/master). But I recently came across this branching guide which made a lot of sense to me. You can download a pdf of the diagram here. As I am simulating a proper development process with the HomeLibrary application, I thought I should probably use some sensible branching principles.

So, my first (and only) step at this point was to create a development branch called develop and to commit my development work against that. I’ve also tagged the commit where the code branched as v0.1.0.0.. Had I been following this guide from the start, that tag would be my very first commit. Anyhow, I’m on track now with a branch/release management strategy. If I was to carve a snapshot out of that diagram, what I have done so far would be:
NewBranch

My next post will be a slice through the layers to display some simple data on a form; kind of a litmus test for my architecture so far.