JavaScript Number#even and Number#odd, Useful JavaScript Game Extensions #33 and #34

Wow, it’s been a while! But enough with the small talk, time for some more simple JavaScript extensions!

###*
Returns true if this number is even (evenly divisible by 2).
 
@name even
@methodOf Number#
 
@type Boolean
@returns true if this number is an even integer, false otherwise.
###
Number::even = ->
  this % 2 == 0
 
###*
Returns true if this number is odd (has remainder of 1 when divided by 2).
 
@name odd
@methodOf Number#
 
@type Boolean
@returns true if this number is an odd integer, false otherwise.
###
Number::odd = ->
  if this > 0
    this % 2 == 1
  else
    this % 2 == -1

These are just a couple of simple methods so you can do things like if exponent.even() to make code quite a bit more readable. The only trick is for Number#odd, due to the way the default mod operator works in JavaScript it would be a pain to check if a negative number were odd without this helper.

Stay tuned for the next 222 parts of the series!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>