Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a Range in CoffeeScript

Tags:

coffeescript

I understand how to define an array range in CoffeeScript

lng[1..10]

However if I have

data = 10

What's the best way to find if 10 is within a range of 1 and 11?

if data is between(1..11)
  return true
like image 852
Charlie Davies Avatar asked Jun 10 '12 12:06

Charlie Davies


2 Answers

There is no "between" keyword, but you can utilize a normal array-range:

if data in [1..11]
    alert 'yay'

But that's a bit of an overkill, so in simple cases I'd recommend a normal comparison:

if 1 <= data <= 11
    alert 'yay'
like image 145
Niko Avatar answered Sep 21 '22 09:09

Niko


If you don't mind polluting the native prototypes, you can add a between method to the Number objects:

Number::between = (min, max) -> 
  min <= this <= max

if 10.between(1, 11)
  alert 'yay'

Although i personally wouldn't use it. if 1 <= something <= 11 is more direct and everyone will understand it. The between method, instead, has to be looked up if you want to know what it does (or you'd have to guess), and i think it doesn't add that much.

like image 20
epidemian Avatar answered Sep 19 '22 09:09

epidemian