Scoped comprehensions are back out, Do is back in.

This commit is contained in:
Jeremy Ashkenas
2010-12-24 08:59:30 -08:00
parent 97f8e9ce1c
commit 094b876a38
10 changed files with 219 additions and 287 deletions

View File

@@ -76,9 +76,10 @@ all = 1
# Ensure that the closure wrapper preserves local variables.
obj = {}
for method in ['one', 'two', 'three'] ->
obj[method] = ->
"I'm " + method
for method in ['one', 'two', 'three']
do (method) ->
obj[method] = ->
"I'm " + method
ok obj.one() is "I'm one"
ok obj.two() is "I'm two"
@@ -94,8 +95,9 @@ ok i is 4
# Ensure that local variables are closed over for range comprehensions.
funcs = for i in [1..3] ->
-> -i
funcs = for i in [1..3]
do (i) ->
-> -i
eq (func() for func in funcs).join(' '), '-1 -2 -3'
ok i is 4
@@ -104,8 +106,9 @@ ok i is 4
# Even when referenced in the filter.
list = ['one', 'two', 'three']
methods = for num, i in list when num isnt 'two' and i isnt 1 ->
-> num + ' ' + i
methods = for num, i in list when num isnt 'two' and i isnt 1
do (num, i) ->
-> num + ' ' + i
ok methods.length is 2
ok methods[0]() is 'one 0'
@@ -115,19 +118,21 @@ ok methods[1]() is 'three 2'
# Even a convoluted one.
funcs = []
for i in [1..3] ->
x = i * 2
((z)->
funcs.push -> z + ' ' + i
)(x)
for i in [1..3]
do (i) ->
x = i * 2
((z)->
funcs.push -> z + ' ' + i
)(x)
ok (func() for func in funcs).join(', ') is '2 1, 4 2, 6 3'
funcs = []
results = for i in [1..3] ->
z = (x * 3 for x in [1..i])
((a, b, c) -> [a, b, c].join(' ')).apply this, z
results = for i in [1..3]
do (i) ->
z = (x * 3 for x in [1..i])
((a, b, c) -> [a, b, c].join(' ')).apply this, z
ok results.join(', ') is '3 , 3 6 , 3 6 9'
@@ -139,9 +144,11 @@ ok(num % 2 is 0 for num in array by 2)
# Nested shared scopes.
foo = ->
for i in [0..7] =>
for j in [0..7] =>
-> i + j
for i in [0..7]
do (i) ->
for j in [0..7]
do (j) ->
-> i + j
eq foo()[3][4](), 7
@@ -150,7 +157,9 @@ eq foo()[3][4](), 7
a = [[0], [1]]
funcs = []
for [v] in a -> funcs.push -> v
for [v] in a
do (v) ->
funcs.push -> v
eq funcs[0](), 0
eq funcs[1](), 1
@@ -268,9 +277,10 @@ funcs = []
list = ->
[1, 2, 3]
for y in list() ->
z = y
funcs.push -> "y is #{y} and z is #{z}"
for y in list()
do (y) ->
z = y
funcs.push -> "y is #{y} and z is #{z}"
eq funcs[1](), "y is 2 and z is 2"
@@ -293,13 +303,17 @@ arrayEq (break for [1..10]), []
# Comprehensions over function literals.
a = 0
for f in [-> a = 1] -> f()
for f in [-> a = 1]
do (f) ->
do f
eq a, 1
# Comprehensions that mention arguments.
list = [arguments: 10]
args = for f in list -> f.arguments
args = for f in list
do (f) ->
f.arguments
eq args[0], 10