views:

60

answers:

2

I have a javascript array of Date objects, which I'd like to test for ascendingness. This is what I built, but I am kind of disappointed by it. Any suggestion?

function isAscending(timeLine) {
  if (timeLine.length < 2)
    return true;

  for(var i=1; i < timeLine.length; i++) {
    if(timeLine[i-1] > timeLine[i])
      return false;
  }
  return true;   
}

(I was hoping for something more expressive, built-in, some library math function etc.)

+3  A: 

That's the simplest way to do it; don't be disappointed.

SLaks
+1 for the positive spirit, Christmas time eh? :o)
Felix Ogg
A: 

How about

function isAscending(timeLine){
    var i=0, L= timeLine.length-1;
    while(i<L){
     if(timeLine[i]> timeLine[++i]) return false;
    }
    return true;
}
kennebec
How is this better?
SLaks
It only reads the length of the array once, rather than on each pass through the loop. And it saves a separate test for an array with one member.
kennebec
He's asking for something easier to read; this isn't.
SLaks
this is indeed the "optimized" version of what I did myself. Less readable and still O(N) complexity (so no impressive benefit). But thanks for the effort anyhow.
Felix Ogg