0

I've just started an exercise in Chapter 4 of a book called Eloquent JavaScript. The exercise asks me to do the following:

"Write a range function that takes two arguments, start and end, and returns an array containing all the numbers from start up to (and including) end."

However, when I write the following code:

function range(start, end) {
  array = [];
for (var i = start; i <= end; i += 1) {
  array.push(i);
}
  return array;
}

console.log(range(5, 2));

It returns square brackets ( [] ). Does anyone know what the issue might be? Thanks a bunch!

Jelani Thompson
  • 332
  • 4
  • 14
  • You can't start at 5 and end at 2 if you're _increasing_ the index - makes no sense. It's like trying to walk backwards and forwards at the same time. Try swapping 5 and 2 and see what happens. – Andy Jun 19 '15 at 13:18
  • 1
    `start` shouldn't be greater than `end` – mic4ael Jun 19 '15 at 13:18
  • Oh, that was dumb of me >_>. And to think that I spent such a long time thinking it was something else. Thanks for the help! – Jelani Thompson Jun 19 '15 at 13:27

2 Answers2

2

You are passing the range indexes in the wrong order. You cant go from 5 to 2, you need to go from 2 to 5

range(2,5)
PhilVarg
  • 4,762
  • 2
  • 19
  • 37
0

Returning square brackets indicates an empty list. This may or may not be the desired result.

To expand on your question a bit - you could use a range function that is more flexible and able to produce descending lists. See below for example, or in this fiddle.

function range(start, end) {
    array = [];
    // Determine order
    var delta = (start < end)? 1 : -1;

    for (var i = start; num_compare(i,end,delta); i += delta) {
        array.push(i);
    }
    return array;
}

function num_compare(a,b, delta) {
    if(delta == 0) { return false; } // No change? Avoid infinite loop.
    if(delta < 0)  { return a >= b; } // Descending. Continue while a>=b
    if(delta > 0)  { return a <= b; } // Asecending. Continue while a<=b
}

var answer = range(5,2);
console.log(answer);
document.getElementById("answer").innerHTML = answer.toString();

Now passing in range(5,2); will produce the (maybe desired) list of [5,4,3,2].

Related questions/answers of note include: reversing order in for loop, comparison operators

Community
  • 1
  • 1
sqsinger
  • 500
  • 1
  • 3
  • 13