Javascript is functional…

When browsing through some code on one of our pages, I noticed the following code:

function selectAllCheckboxes() {
	var count = 0;
	var checkboxes = document.getElementsByTagName("input");
	for (var i = 0; i < checkboxes.length; i++) {
		var element = checkboxes[i];
		if (element.type == 'checkbox') {
			element.checked = true;
               ++count;
		}
	}
        updateSelectedCheckboxCount(count);
}

function unselectAllCheckboxes() {
	var checkboxes = document.getElementsByTagName("input");
	for (var i = 0; i < checkboxes.length; i++) {
		var element = checkboxes[i];
		if (element.type == 'checkbox') {
			element.checked = false;
		}
	}
	updateSelectedCheckboxCount(count);
}

function updateSelectedCheckboxCount() {
	var count = 0;
	// count the number of checkboxes selected on the page
	var checkboxes = document.getElementsByTagName("input");
	for (var i = 0; i < checkboxes.length; i++) {
		var element = checkboxes[i];
		if (element.type == 'checkbox') {
			if (element.checked == true) {
				++count;
			}
		}
	}
        updateSelectedCheckboxCount(count);
}

There’s a lot of duplication there, and only 1 or 2 lines unique to each function. So I refactored the code to take advantage of the fact that Javascript supports passing functions.

Here’s the modified code.

function selectAllCheckboxes() {
	processCheckboxes( function(checkbox) { checkbox.checked = true; ++count;} );
}

function unselectAllCheckboxes() {
	processCheckboxes( function(checkbox) { checkbox.checked = false;} );
}

function updateSelectedCheckboxCount() {
	processCheckboxes( function(checkbox) { if(checkbox.checked) { ++count; } );
}

function processCheckboxes(checkboxProcessFunction) {
	count = 0;
	var ulField = document.getElementById("permission.list");

	var checkboxes = ulField.getElementsByTagName("input");
	for (var i = 0; i < checkboxes.length; i++) {
		var element = checkboxes[i];
		if (element.type == 'checkbox') {
			checkboxProcessFunction(element);
		}
	}
	setSelectedCount();
}

This way, if the process of getting checkboxes can be improved, the code only has to be changed in one place.

So, don’t forget that javascript is a functional language…

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply