On Sun, 5 Dec 2004 11:03:01 +0200, J. J. Cale <ph****@netvision.net.il>

wrote:

In IE6 both these functions *seem* to be working.

An important thing to note is that they depend on at least one element in

the array. The behaviour the two alternatives is also very different. The

first version will return a reference to the left-most element, or

undefined if there are no elements in the array. The second version will

return smallest offset value, or false if there are no elements in the

array.

[snip]

Besides the obvious stack problems that can occur if one recurses too

deep are there other reasons for this that I should know about?

Recursion tends to be inefficient as function calls have the overhead of

setting up a new execution context. Loops are quicker.

[snip]

getSmallest(document.getElementsByTagName(tagName) );

function getSmallest(aArr) {

var small = aArr[0];

for (var i=1; i < aArr.length; i++) {

if(aArr[i].offsetLeft >= small.offsetLeft)

continue;

else small = aArr[i];

Why not

for(var i = 1, n = aArr.length; i < n; ++i) {

/* This being the most significant change: */

if(aArr[i].offsetLeft < small.offsetLeft) {

small = aArr[i];

}

}

}

return small;

}

#2 recursion

var a = document.getElementsByTagName(tagName);

getSmallest( a, a.length-1);

function getSmallest(aArr, n) {

if (n < 0) return false;

if(n == aArr.length-1) smallest = n;

smallest = aArr[smallest].offsetLeft <= aArr[n].offsetLeft?

smallest: n;

if(getSmallest(aArr,n-1))

This would also evaluate to false if the offset value returned below was

zero.

return aArr[smallest].offsetLeft;

return aArr[smallest].offsetLeft;

That's bizarre: if the result from the recursive call evaluates to true,

return the smallest offset value. Otherwise, return the same thing.

}

This is a much reduced version, but it too differs from both previous

versions. :) It will return the array index of the left-most elements, or

-1 if there are no elements in the array.

function getSmallest(arr, n) {var s;

if(n < 0) {return arr.length ? 0 : -1;}

s = getSmallest(arr, n - 1);

return (arr[n].offsetLeft < arr[s].offsetLeft) ? n : s;

}

getSmallest(arr, arr.length - 1);

Really, I'd just stick to the loop version.

Mike

--

Michael Winter

Replace ".invalid" with ".uk" to reply by e-mail.