Computer >> Computer tutorials >  >> Programming >> Javascript

Split a range of number to a specific number of intervals JavaScript


Suppose we have an interval that always starts from 0 and ends at some positive integer n, lets denote the interval with an array like this −

const interval = [0, n];

Or simply, since we know that the range will always start at 0, lets denote the interval by only the upper limit.

const interval = n;

We are required to write a JavaScript function that takes in two numbers as first and the second argument.

The first argument represents an interval starting from 0 and end at that number. And the second number determines how many equal intervals (if possible) we have to create between the actual interval.

For example: If the input arguments are 3 and 2.

Then the actual interval is [0, 3] = [0, 1, 2, 3] and we have to divide this into 2 equal intervals (if possible)

Therefore, for these inputs the output should be −

const output = [
[0, 1],
[2, 3]
];

Note that the upper and lower limits of intervals are always whole numbers.

The code for this will be −

Example

const getIntervals = (interval, num) => {
   const size = Math.floor(interval / num);
   const res = [];
   for (let i = 0; i <= interval;
   i += size) {
      const a = i == 0 ? i : i += 1;
      const b = i + size > interval ? interval : i + size;
      if (a < interval){
         res.push([a, b]);
      };
   };
   return res;
};
console.log(getIntervals(3, 2));

Output

And the output in the console will be −

[
[0, 1],
[2, 3]
]