Skip to content

Instantly share code, notes, and snippets.

@shesek
Created February 27, 2012 09:16
Show Gist options
  • Save shesek/1922656 to your computer and use it in GitHub Desktop.
Save shesek/1922656 to your computer and use it in GitHub Desktop.
CoffeeScript iteration helper
## Version 1 ##
# To continue to the next iteration, `return` instead of `continue`
# To stop iteration, `throw StopIteration` instead of `break`
StopIteration = {}
iter = (iterator, func) ->
try loop func do iterator
catch e then throw e unless e is StopIteration
return
# Usage
range_iterator = (current, max) -> ->
throw StopIteration if current > max
current++
iter (range_iterator 5, 15), (val) ->
return if val%2 is 0
alert val
## Version 2 ##
# To continue to the next iteration, `@continue()` instead of `continue`
# To stop iteration, `@break()` instead of `break`
# To return from the `iter` call, use `@return`
iter = do ->
StopIteration = {}
NextIteration = {}
ReturnValue = (@val) ->
helpers =
continue: -> throw NextIteration
break: -> throw StopIteration
return: (val) -> throw new ReturnValue val
(iterator, func) ->
try loop
try func.call helpers, iterator.call helpers
catch e then throw e unless e is NextIteration
catch e
return e.val if e instanceof ReturnValue
throw e unless e is StopIteration
return
# Usage
range_iterator = (current, max) -> ->
@break() if current > max
current++
iter (range_iterator 5, 15), (val) ->
@continue() if val%2 is 0
alert val
alert iter (range_iterator 5, 15), (val) ->
@return val + 1 if val%6 is 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment