0

This question is similar to an existing one: Create array of all integers between two numbers, inclusive, in Javascript/jQuery

However, instead of simply generating a range between two bounds min and max, I'd like to create a range between to numbers start and end with a specified limit.

Example:

start 19
end 30
limit 60

Result: [19, 20, 21, 22, ..., 28, 29, 30]

Whereas
start 30   <--\
end 19       <--/
limit 60

Result: [30, 31, 32, ..., 58, 59, 60, 1, 2, 3, ..., 17, 18, 19]

Note that: No element of the array can ever be greater than limit.

I'm guessing I'd also have to define a lower limit (1 in this case to exclude zero fro the array).

How can I achieve this in plain ES6?

FZs
  • 16,581
  • 13
  • 41
  • 50
j3141592653589793238
  • 1,810
  • 2
  • 16
  • 38

1 Answers1

0

Here's my implementation of this, maybe not the best one, but it works.

It determines the direction of the range using Math.sign(end-start), and has min and max parameters:

const range = ({
  start,
  end,
  min = -Infinity,
  max = Infinity
}) => {
  if(Math.floor(start) !== start || Math.floor(end) !== end) throw new Error('Invalid numbers')
  const 
    sign = Math.sign(end - start),
    arr = [],
    push = n => {
      if (min <= n && n <= max) arr.push(n)
    }
  for (let n = start; n !== end; n += sign)
    push(n)
  push(end)
  return arr
}

console.log(range({start: 30, end: 19, max: 60}))
FZs
  • 16,581
  • 13
  • 41
  • 50