Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.

 

senocular.com ActionScript Library

sortChildren.as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Removes and returns an XML node based on index
XMLNode.prototype.extractChild = function(i){
	var n = this.childNodes<i>.cloneNode(true);
	this.childNodes<i>.removeNode();
	return n;
}

// Swap the positions of two child nodes within their parent's childNodes array
XMLNode.prototype.swapChildren = function(i, i2){
	if (i==i2) return(0);
	if (i > i2){
		var temp = i;
		i = i2; i2 = temp;
	}
	var n = this.extractChild(i);
	var n2 = this.extractChild(i2-1);
	this.insertBefore(n2, this.childNodes<i>);
	this.insertBefore(n, this.childNodes[i2]);
}

// Sort child nodes based on a compare function (uses a simple quicksort)
XMLNode.prototype.sortChildren = function(cmp, low,high) {
	var a = this.childNodes;
	if (cmp == undefined) cmp = this.sortChildren.defaultCompare;
	if (low == undefined) low = 0;
	if (high == undefined) high = a.length;
	var p = a[low], w = low+1, h = high;
	while(w < h) {
		if (cmp(a[w], p)) w++;
		else this.swapChildren(w, (--h));
	}
	this.swapChildren(low, (--w));
	if (w-low > 1) this.sortChildren(cmp, low, w);
	if (high-h > 1) this.sortChildren(cmp, h, high);
}
 
// A default sort function for use in sortChildren
XMLNode.prototype.sortChildren.defaultCompare = function(a,b){
	return a.nodeName <= b.nodeName;
}