Skip to content

Instantly share code, notes, and snippets.

@m242
Created September 9, 2011 06:01
Show Gist options
  • Save m242/1205571 to your computer and use it in GitHub Desktop.
Save m242/1205571 to your computer and use it in GitHub Desktop.
Scala Option in CoffeeScript
Array::filter = (f) -> (x for x in @ when f(x))
Number::filter = (f) -> [@.valueOf()].filter f
String::filter = Number::filter
Object::filter = (f) -> if f(@) then @ else null
Array::foreach = (f) -> (f(x) for x in @)
Number::foreach = (f) -> [@.valueOf()].foreach f
String::foreach = Number::foreach
Object::foreach = (f) -> if @ then f(@) else null
Array::exists = (f) -> (
for item in @
if f(item) then return true
false
)
Number::exists = (f) -> [@.valueOf()].exists f
String::exists = Number::exists
Object::exists = (f) -> f(@)
Array::map = (f) -> ((f(x) for x in @))
Number::map = (f) -> [@.valueOf()].map f
String::map = Number::map
Object::map = (f) -> if @ then f(@) else null
class MyOption
constructor: (@item) ->
getOrElse: (def) -> if @item? then @item else def
exists: (f) -> @item?.exists f
get: -> @item
isDefined: -> @item?
isEmpty: -> !@item?
filter: (f) -> @item?.filter f
foreach: (f) -> @item?.foreach f
map: (f) -> @item?.map f
orElse: (def) -> if @item? then @ else def
orNull: -> if @item? then @ else null
Option = (x) -> new MyOption(x)
$ ->
x = "Yes"
y = null
alert Option(x).getOrElse("No")
alert Option(y).getOrElse("No")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment