2010-01-13 20:59:57 -05:00
|
|
|
x: 1
|
|
|
|
y: {}
|
2010-01-26 10:52:05 -05:00
|
|
|
y.x: -> 3
|
2010-01-13 20:59:57 -05:00
|
|
|
|
2010-01-29 23:30:54 -05:00
|
|
|
puts x is 1
|
|
|
|
puts typeof(y.x) is 'function'
|
|
|
|
puts y.x instanceof Function
|
|
|
|
puts y.x() is 3
|
|
|
|
puts y.x.name is 'x'
|
2010-01-13 20:59:57 -05:00
|
|
|
|
|
|
|
|
2010-01-16 15:02:04 -05:00
|
|
|
# The empty function should not cause a syntax error.
|
2010-01-26 10:52:05 -05:00
|
|
|
->
|
2010-02-15 18:03:00 -05:00
|
|
|
() ->
|
2010-01-16 15:02:04 -05:00
|
|
|
|
|
|
|
|
2010-01-13 20:59:57 -05:00
|
|
|
obj: {
|
|
|
|
name: "Fred"
|
|
|
|
|
2010-01-26 10:52:05 -05:00
|
|
|
bound: ->
|
2010-01-29 23:30:54 -05:00
|
|
|
(=> puts(this.name is "Fred"))()
|
2010-01-13 20:59:57 -05:00
|
|
|
|
2010-01-26 10:52:05 -05:00
|
|
|
unbound: ->
|
2010-01-29 23:30:54 -05:00
|
|
|
(-> puts(!this.name?))()
|
2010-01-13 20:59:57 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
obj.unbound()
|
2010-01-16 11:24:10 -05:00
|
|
|
obj.bound()
|
2010-01-16 15:44:07 -05:00
|
|
|
|
|
|
|
|
|
|
|
# The named function should be cleared out before a call occurs:
|
|
|
|
|
|
|
|
# Python decorator style wrapper that memoizes any function
|
2010-01-26 10:52:05 -05:00
|
|
|
memoize: (fn) ->
|
2010-01-16 15:44:07 -05:00
|
|
|
cache: {}
|
|
|
|
self: this
|
2010-01-26 10:52:05 -05:00
|
|
|
(args...) ->
|
2010-01-16 15:44:07 -05:00
|
|
|
key: args.toString()
|
|
|
|
return cache[key] if cache[key]
|
|
|
|
cache[key] = fn.apply(self, args)
|
|
|
|
|
|
|
|
Math: {
|
2010-01-26 10:52:05 -05:00
|
|
|
Add: (a, b) -> a + b
|
|
|
|
AnonymousAdd: ((a, b) -> a + b)
|
|
|
|
FastAdd: memoize (a, b) -> a + b
|
2010-01-16 15:44:07 -05:00
|
|
|
}
|
|
|
|
|
2010-01-29 23:30:54 -05:00
|
|
|
puts Math.Add(5, 5) is 10
|
|
|
|
puts Math.AnonymousAdd(10, 10) is 20
|
|
|
|
puts Math.FastAdd(20, 20) is 40
|
2010-01-24 23:56:27 -05:00
|
|
|
|
|
|
|
|
|
|
|
# Parens are optional on simple function calls.
|
2010-01-29 23:30:54 -05:00
|
|
|
puts 100 > 1 if 1 > 0
|
|
|
|
puts true unless false
|
|
|
|
puts true for i in [1..3]
|
2010-01-26 02:27:19 -05:00
|
|
|
|
2010-01-29 23:30:54 -05:00
|
|
|
puts_func: (f) -> puts(f())
|
|
|
|
puts_func -> true
|
2010-01-26 14:49:33 -05:00
|
|
|
|
|
|
|
# Optional parens can be used in a nested fashion.
|
|
|
|
call: (func) -> func()
|
|
|
|
|
|
|
|
result: call ->
|
|
|
|
inner: call ->
|
|
|
|
Math.Add(5, 5)
|
|
|
|
|
2010-01-29 23:30:54 -05:00
|
|
|
puts result is 10
|
2010-01-26 21:15:56 -05:00
|
|
|
|
|
|
|
|
|
|
|
# And even with strange things like this:
|
|
|
|
|
|
|
|
funcs: [(x) -> x, (x) -> x * x]
|
|
|
|
result: funcs[1] 5
|
|
|
|
|
2010-01-29 23:30:54 -05:00
|
|
|
puts result is 25
|
2010-01-26 21:15:56 -05:00
|
|
|
|
|
|
|
result: ("hello".slice) 3
|
|
|
|
|
2010-01-29 23:30:54 -05:00
|
|
|
puts result is 'lo'
|