Skip to content

Instantly share code, notes, and snippets.

@haltcase
Created March 15, 2017 03:11
Show Gist options
  • Save haltcase/12ff1d78f712923cc2154bd361850963 to your computer and use it in GitHub Desktop.
Save haltcase/12ff1d78f712923cc2154bd361850963 to your computer and use it in GitHub Desktop.
Code golfing the crap out of a JavaScript `range()` function.

A function that does this:

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

Let's do it in < 100 bytes!

let range=(s,e,n=1)=>(e==null?(e=s,s=0):0,Array.from({length:Math.abs(~~(e-s)/n)},(v,i)=>i?i*n:s))

Here's a readable version:

let rangeReadable = (start, end, step = 1) => {
  return (
    end == null ? (end = start, start = 0) : 0,
    Array.from({ length: Math.abs(~~(end - start) / n) }, (v, i) => i ? i * step : step)
  )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment