Random Integer lower bound
smaspe opened this issue · 2 comments
smaspe commented
in http://coffeescriptcookbook.com/chapters/math/random-integer
there is this
if not lower?
[lower, upper] = [0, lower]
If lower does not exist, how can it be considered to use it as upper value?
(I considered using [0, upper], but since upper is after lower in the arguments, It would have its default value anyway. Number.MAX_VALUE, may be?)
sukima commented
By using the lower variable you can use this function with one argument. It's a bit cryptic. A better way to write it might be:
randomInt = (lower, upper) ->
[lower, upper] = [0, lower] unless upper? # Called with one argument
[lower, upper] = [upper, lower] if lower > upper # Lower must be less then upper
Math.floor(Math.random() * (upper - lower + 1) + lower) # Last statement is a return value
randomInt(3, 15) # => between 3 and 15
randomInt(15, 3) # => between 3 and 15
randomInt(5) # => between 0 and 5