Last Updated: February 25, 2016
·
827
· mlb

Array.range generator

Here comes a simple little function that can help you to build range-arrays (useful if you use a functional coding-style)

Array.range = function(start, end){

  if(typeof start != "number") return []

  var hasEnd = typeof end == "number"
    , leftToRight
    , result = []

  end = hasEnd ? end : start
  start = hasEnd ? start : 0
  leftToRight = start < end

  if(leftToRight) for(;start <= end; start++) result.push(start)
  else for(;start >= end; start--) result.push(start)

  return result
}


Array.range(3,10) //  [3, 4, 5, 6, 7, 8, 9, 10]
Array.range(10, 3) // [10, 9, 8, 7, 6, 5, 4, 3]
Array.range(10) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside