Skip to content

Instantly share code, notes, and snippets.

@shesek
Created March 1, 2012 20:48
Show Gist options
  • Save shesek/1953135 to your computer and use it in GitHub Desktop.
Save shesek/1953135 to your computer and use it in GitHub Desktop.
CoffeeScript: Returning from internal anonymous functions
# Allows return values to be returned from anonymous functions within other functions. The function that
# the value should be returned from should be decorated with the `catchx` function, and the value should
# be returned using the `returnx` function. This is done by throwing the return value using `returnx`,
# than catching it inside the decorator and `return`ing it.
# Was previously part of a specific solution for iterators at https://gist.github.com/1953057
catchx = returnx = null
do ->
ReturnValue = (@val) ->
returnx = (val) -> throw new ReturnValue val
catchx = (func) -> ->
try func.apply this, arguments
catch e
return e.val if e instanceof ReturnValue
throw e
# Usage:
find = catchx (arr) ->
arr.forEach (v) -> returnx v if v%5 is 0
alert find [3..7]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment