1
0
Fork 0
mirror of https://github.com/jashkenas/coffeescript.git synced 2022-11-09 12:23:24 -05:00
jashkenas--coffeescript/test/test_existence.coffee

106 lines
1.7 KiB
CoffeeScript
Raw Normal View History

ok(if mySpecialVariable? then false else true)
2010-01-01 12:41:55 -05:00
2010-07-25 01:23:37 -04:00
mySpecialVariable = false
2010-01-01 12:41:55 -05:00
ok(if mySpecialVariable? then true else false)
# Existential assignment.
2010-07-25 01:23:37 -04:00
a = 5
a = null
a ?= 10
b ?= 10
ok a is 10 and b is 10
# The existential operator.
2010-07-25 01:23:37 -04:00
z = null
x = z ? "EX"
ok z is null and x is "EX"
# Only evaluate once.
2010-07-25 01:23:37 -04:00
counter = 0
getNextNode = ->
throw "up" if counter
counter++
ok(if getNextNode()? then true else false)
# Existence chains, soaking up undefined properties:
2010-07-25 01:23:37 -04:00
obj = {
prop: "hello"
}
ok obj?.prop is "hello"
ok obj?['prop'] is "hello"
ok obj.prop?.length is 5
ok obj?['prop']?['length'] is 5
ok obj?.prop?.non?.existent?.property is undefined
ok obj?['non']?['existent'].property is undefined
# Soaks and caches method calls as well.
2010-07-25 01:23:37 -04:00
arr = ["--", "----"]
ok arr.pop()?.length is 4
ok arr.pop()?.length is 2
ok arr.pop()?.length is undefined
ok arr[0]?.length is undefined
ok arr.pop()?.length?.non?.existent()?.property is undefined
# Soaks method calls safely.
2010-07-25 01:23:37 -04:00
value = undefined
result = value?.toString().toLowerCase()
ok result is undefined
2010-07-25 01:23:37 -04:00
value = 10
result = value?.toString().toLowerCase()
ok result is '10'
2010-08-14 11:29:10 -04:00
# Soaks inner values.
ident = (obj) -> obj
ok ident(non?.existent().method()) is undefined
# Soaks constructor invocations.
2010-07-25 01:23:37 -04:00
a = 0
class Foo
constructor: -> a += 1
bar: "bat"
ok (new Foo())?.bar is 'bat'
ok a is 1
# Safely existence test on soaks.
2010-07-25 01:23:37 -04:00
result = not value?.property?
ok result
# Safely calls values off of non-existent variables.
2010-07-25 01:23:37 -04:00
result = nothing?.value
ok result is undefined
# Assign to the result of an exsitential operation with a minus.
2010-07-25 01:23:37 -04:00
x = null ? - 1
ok x is - 1
# Things that compile to ternaries should force parentheses, like operators do.
2010-07-25 01:23:37 -04:00
duration = if options?.animated then 150 else 0
ok duration is 0