Skip to content

Instantly share code, notes, and snippets.

@shesek
Created March 1, 2012 20:35
Show Gist options
  • Save shesek/1953057 to your computer and use it in GitHub Desktop.
Save shesek/1953057 to your computer and use it in GitHub Desktop.
CoffeeScript iteration helper - with "return exception" decorator
# With a `returnex` function decorator for returning exception values
# Previous versions at https://gist.github.com/1922656
iter = returnex = null
do ->
StopIteration = {}
NextIteration = {}
ReturnValue = (@val) ->
helpers =
continue: -> throw NextIteration
break: -> throw StopIteration
return: (val) -> throw new ReturnValue val
returnex = (func) -> ->
try func.apply this, arguments
catch e
return e.val if e instanceof ReturnValue
throw e
iter = (iterator, func) ->
try loop
try func.call helpers, iterator.call helpers
catch e then throw e unless e is NextIteration
catch e then throw e unless e is StopIteration
return
# Usage
range_iterator = (current, max) -> ->
@break() if current > max
current++
f = returnex (min, max) ->
iter (range_iterator min, max), (s) ->
@return s if s%7 is 0
return "NEVER FOUND MATCH"
alert [(f 5,9), f(1,3)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment