Skip to content
Advertisement

Create an array with all numbers from min to max without a loop

I have two numbers, min and max, and I want to create an array that contains all number between them (including min and max).

The most obvious approach is to use a for loop for this, and push the single values onto an array. Nevertheless, this seems to be a quite naive approach, i.e. it’s imperative programming.

Now I was thinking of how to create such an array in a more functional style. Basically, something such as the reverse of a reduce function: Instead of reducing an array to a number, building up an array from two numbers.

How could I do this? What is a functional approach to solve this problem?

Basically, I’m thinking of something such as 10..20 in some other languages. What’s the most elegant equivalent for this in JavaScript?

Advertisement

Answer

You can think of a “functional” definition of range:

range(low, hi) = [], if low > hi
range(low, hi) = [low] (+) range(low+1,hi), otherwise,

which leads to the JS definition:

function range(low,hi){
  function rangeRec(low, hi, vals) {
     if(low > hi) return vals;
     vals.push(low);
     return rangeRec(low+1,hi,vals);
  }
  return rangeRec(low,hi,[]);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement