Created
March 1, 2012 20:35
-
-
Save shesek/1953057 to your computer and use it in GitHub Desktop.
CoffeeScript iteration helper - with "return exception" decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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