Archive for the ‘MooTools’ category

Quicksort an array of objects

2009-08-05 – 4:14pm

Often, you will need to sort an array of objects in Javascript. The inbuilt sort() function can’t do this, but here is a Quicksort implementation for doing just this.

Parameters

array The array to be sorted. (See below for an implementation on the Array Native itself, which makes this variable unnecessary).

key The key to sort by. Make sure every object in your array has this key.

Examples

var objs = [
	{fruit:"cherry"},
	{fruit:"apple"},
	{fruit:"banana"}
];

console.log(objs.sortObjects('fruit'));
// Logs [{fruit:"apple"},{fruit:"banana"},{fruit:"cherry"}] to the console

The code

sortObjects: function(array, key) {
	for (var i = 0; i < array.length; i++) {
		var currVal = array[i][key];
		var currElem = array[i];
		var j = i - 1;
		while ((j >= 0) && (array[j][key] > currVal)) {
			array[j + 1] = array[j];
			j--;
		}
		array[j + 1] = currElem;
	}
}

Implemented on the Array native:

Array.implement({
	sortObjects: function(key) {
		for (var i = 0; i < this.length; i++) {
			var currVal = this[i][key];
			var currElem = this[i];
			var j = i - 1;
			while ((j >= 0) && (this[j][key] > currVal)) {
				this[j + 1] = this[j];
				j--;
			}
			this[j + 1] = currElem;
		}
	}
});

Javascript string ellipsising

2009-08-05 – 4:03pm

Putting ellipses into strings that are too long has been around for a very long time. Unfortunately, Javascript doesn’t offer a native method of doing this, so below is a little function that’ll do it for you.

This function returns a copy of the string it’s called on, ellipsised, and takes three parameters:

toLength (required) The number of characters to truncate the string to (or 0 to disable ellipsising)

where (optional, default ‘end’) A string representing where the ellipsis should be placed — ‘front’, ‘middle’, or ‘end’

ellipsis (option, default ‘\u2026′) A string to be used as the ellipsis.

Examples

// Our clichéd string
var s = 'Jackdaws love my great big sphinx of quartz';

alert(s.ellipsise(10));
// Alerts "Jackdaws l…"

alert(s.ellipsise(10, 'front'));
// Alerts "… of quartz"

alert(s.ellipsise(10, 'middle', 'pony'));
// Alerts "Jackdponyuartz"

The code

String.implement({
	ellipsise: function(toLength, where, ellipsis) { // Where is one of ['front','middle','end'] -- default is 'end'
		if (toLength < 1) return this;
		ellipsis = ellipsis || '\u2026';
		if (this.length < toLength) return this;
		switch (where) {
			case 'front':
				return ellipsis + this.substr(this.length - toLength);
				break;
			case 'middle':
				return this.substr(0, toLength / 2) + ellipsis + this.substr(this.length - toLength / 2)
				break;
			case 'end':
			default:
				return this.substr(0, toLength) + ellipsis;
				break;
		}
	}
});

If you’re not using MooTools, you can use this variant instead:

String.prototype.ellipsise = function(toLength, where, ellipsis) { // Where is one of ['front','middle','end'] -- default is 'end'
	if (toLength < 1) return this;
	ellipsis = ellipsis || '\u2026';
	if (this.length < toLength) return this;
	switch (where) {
		case 'front':
			return ellipsis + this.substr(this.length - toLength);
			break;
		case 'middle':
			return this.substr(0, toLength / 2) + ellipsis + this.substr(this.length - toLength / 2)
			break;
		case 'end':
		default:
			return this.substr(0, toLength) + ellipsis;
			break;
	}
}

At work, I’ve recently been putting together a nice little calendar-like utility using Javascript. Basically, it has to generate a table consisting of cells which may span multiple rows. Surely the solution is simple enough: just set the rowspan on each td as we create it. Unfortunately, that doesn’t work, at least not in Firefox.

It appears that in Firefox, if you create a td and set its rowspan to some value when there are no rows for it to expand into, the attribute will be completely ignored, even if you add rows afterwards! Needless to say, this is very annoying. The solution? Build your table backwards.

The code I have now is something like this (note that I’m developing using the Mootools framework):

var tbl = new Element('table');
var trs = new Array();

for (var i = 0; i < 4; i++) {
  var tr = new Element('tr');
  tr.grab(new Element('td', {
    'html': 'Cell ' + i
  }));
  if (i % 2 == 0) {
    tr.grab(new Element('td', {
      'rowspan': 2,
      'html': 'Span ' + (i / 2)
    }));
  }
  trs.push(tr);
}

for (var i = trs.length - 1; i >= 0; i--) {
  tbl.grab(trs[i], 'top');
}

What does this code do? Well basically, we’re creating a table with ten rows and two columns; the cells in the right-hand column each occupy two rows. The result will be something like this:

Cell 1 Span 1
Cell 2
Cell 3 Span 2
Cell 4

I’ve started work on a new project at my job — a fairly complex AJAX application for the education sector. For this project, I’ve been allowed to essentially choose my own direction, and I’ve chosen to implement the clientside Javascript using the MooTools framework. I’ll say it right here: I’m absolutely loving it.

What I’m really enjoying about MooTools is the object-orientedness it brings to development. Although syntactically it’s a little bit weird at first, the ability to create, extend, and implement classes makes my development progress much more quickly, and in a more efficient way. Add to that the plethora of utilities (like the .each prototype for arrays) and shorthand functions (like $ to replace document.getElementById), and all of a sudden Javascript development becomes a bit more, well, flexible.

I’m not saying that you can’t accomplish cool things in Javascript outside of MooTools (or other frameworks, for that matter); my point is that I believe you can accomplish cool things in Javascript more quickly using a good framework, which should really come as no surprise. Perhaps the reason I’m so enjoying this type of development, to the point of blogging about it, is that up till now, I’ve been stuck working in a non-frameworked, very non-OO Javascript development paradigm.

I mentioned the curious syntax that accompanies MooTools.  To create a new class, for example, you would probably write something like this:

var myClass = new Class({
  Implements: Options,
  options: {
    optionA: 'monkey',
    optionB: 'pony'
  },
  initializer: function(options) {
    this.setOptions(options);
    this.doSomeStuff();
  },
  doSomeStuff: function() {
    alert(this.options.optionA + ' eats ' + this.options.optionsB);
  }
});

And then you would initialise it like this:

var myInstance = new myClass({
  optionA: 'Big Pony'
});

Although it looks a bit weird, it’s actually not too bad. There are really only two problems I have with it:

  1. Remembering to put commas in all the right spots.
  2. Geany, my preferred IDE (cf. Geany IDE: Tango dark colour scheme) can’t pick up classes and members properly (actually, at all) in this style.

Other than that, though, I’m really enjoying it.