2
votes

I'm trying to implement a function which takes three arguments(min, max, step)and generates a range of integers from min to max, with the step. The first integer is the minimum value, the second is the maximum of the range and the third is the step.

Here is an example of what it should look like: generateRange(2, 10, 2) should return array of [2,4,6,8,10].

I'm using the splice method to remove any existing elements in the array that are greater than the max argument.

function generateRange(min, max, step) {
  var arr = [];
  var count = min;
  for (var i = 0; i < max / step; i++) {
    arr[i] = count;
    count = count + step;
    arr[i] > max ? arr.splice(i, 1) : arr[i];
  }
  return arr;
}

console.log(generateRange(2, 10, 2));

Whenever I console.log my result I get a bunch of commas after the last item...so it looks like this: [2,4,6,8,10, , , , ]

It doesn't appear to be deleting the items. What am I missing? Thanks!

1
everything work fine when I run the code: [2, 4, 6, 8, 10] - Marcin
Why dont you just increment until (max - max%step)/step instead of doing that splicing nonsense - Luke Kot-Zaniewski
Why are you using a ternary operator when the value of the expression isn't being used? Just use an if statement. - Barmar
Your array starts out empty. There are no existing elements to remove. - Barmar

1 Answers

2
votes

The ternary operator is a bit strange, as the expression is not stored. It fixes the array by removing too large values. That works once, but if there is a second time, i will have increased, and by the assignment to arr[i], the array's length is again as if there had been no splice performed before (except for the undefined value at that i-1 index).

It would be better to exit the loop before assigning a value that is outside of the range. There is no sense in continuing the loop in such a case.

So make the count variable your loop variable and condition:

function generateRange(min, max, step){
    var arr = [];
    for(var count = min; count <= max; count+=step){
        arr.push(count);
    }
    return arr;
}

var res = generateRange(2, 10, 2);

console.log(res);

A less readable, but shorter ES6 version would be:

function generateRange(min, max, step){
    return Array.from(Array(Math.floor((max-min)/step)+1), (x,i) => min+i*step);
}

let res = generateRange(2, 10, 2);

console.log(res);