Does JavaScript have a method like “range()” to generate a range within the supplied bounds?

后端 未结 30 3238
广开言路
广开言路 2020-11-22 00:51

In PHP, you can do...

range(1, 3); // Array(1, 2, 3)
range(\"A\", \"C\"); // Array(\"A\", \"B\", \"C\")

That is, there is a function that l

30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 01:30

    Handy function to do the trick, run the code snippet below

    function range(start, end, step, offset) {
      
      var len = (Math.abs(end - start) + ((offset || 0) * 2)) / (step || 1) + 1;
      var direction = start < end ? 1 : -1;
      var startingPoint = start - (direction * (offset || 0));
      var stepSize = direction * (step || 1);
      
      return Array(len).fill(0).map(function(_, index) {
        return startingPoint + (stepSize * index);
      });
      
    }
    
    console.log('range(1, 5)=> ' + range(1, 5));
    console.log('range(5, 1)=> ' + range(5, 1));
    console.log('range(5, 5)=> ' + range(5, 5));
    console.log('range(-5, 5)=> ' + range(-5, 5));
    console.log('range(-10, 5, 5)=> ' + range(-10, 5, 5));
    console.log('range(1, 5, 1, 2)=> ' + range(1, 5, 1, 2));

    here is how to use it

    range (Start, End, Step=1, Offset=0);

    • inclusive - forward range(5,10) // [5, 6, 7, 8, 9, 10]
    • inclusive - backward range(10,5) // [10, 9, 8, 7, 6, 5]
    • step - backward range(10,2,2) // [10, 8, 6, 4, 2]
    • exclusive - forward range(5,10,0,-1) // [6, 7, 8, 9] not 5,10 themselves
    • offset - expand range(5,10,0,1) // [4, 5, 6, 7, 8, 9, 10, 11]
    • offset - shrink range(5,10,0,-2) // [7, 8]
    • step - expand range(10,0,2,2) // [12, 10, 8, 6, 4, 2, 0, -2]

    hope you find it useful.


    And here is how it works.

    Basically I'm first calculating the length of the resulting array and create a zero filled array to that length, then fill it with the needed values

    • (step || 1) => And others like this means use the value of step and if it was not provided use 1 instead
    • We start by calculating the length of the result array using (Math.abs(end - start) + ((offset || 0) * 2)) / (step || 1) + 1) to put it simpler (difference* offset in both direction/step)
    • After getting the length, then we create an empty array with initialized values using new Array(length).fill(0); check here
    • Now we have an array [0,0,0,..] to the length we want. We map over it and return a new array with the values we need by using Array.map(function() {})
    • var direction = start < end ? 1 : 0; Obviously if start is not smaller than the end we need to move backward. I mean going from 0 to 5 or vice versa
    • On every iteration, startingPoint + stepSize * index will gives us the value we need

提交回复
热议问题