implemented for-from-to and removed dotted ranges

This commit is contained in:
satyr
2010-10-13 13:53:56 +09:00
parent 2f7c076a50
commit bd10c2f828
21 changed files with 582 additions and 877 deletions

View File

@@ -15,37 +15,15 @@ ok odds.join(' ') is "one! three!"
# Basic range comprehensions.
nums = i * 3 for i in [1..3]
negs = x for x in [-20..-5*2]
negs = negs[0..2]
result = nums.concat(negs).join(', ')
ok result is '3, 6, 9, -20, -19, -18'
ok i is 3
ok x is -10
nums = i * 3 for i from 1 to 3
negs = x for x from -20 to -5*2
eq nums.concat(negs.slice 0, 3).join(' '), '3 6 9 -20 -19 -18'
# With range comprehensions, you can loop in steps.
results = x for x in [0...15] by 5
ok results.join(' ') is '0 5 10'
results = x for x in [0..100] by 10
ok results.join(' ') is '0 10 20 30 40 50 60 70 80 90 100'
# And can loop downwards, with a negative step.
results = x for x in [5..1]
ok results.join(' ') is '5 4 3 2 1'
ok results.join(' ') is [(10-5)..(-2+3)].join(' ')
results = x for x in [10..1]
ok results.join(' ') is [10..1].join(' ')
results = x for x in [10...0] by -2
ok results.join(' ') is [10, 8, 6, 4, 2].join(' ')
eq "#{ x for x from 0 to 9 by 3 }", '0,3,6,9'
eq "#{ x for x from 9 to 0 by -3 }", '9,6,3,0'
eq "#{ x for x from 3*3 to 0*0 by 0-3 }", '9,6,3,0'
# Multiline array comprehension with filter.
@@ -53,13 +31,19 @@ evens = for num in [1, 2, 3, 4, 5, 6] when num % 2 is 0
num *= -1
num -= 2
num * -1
eq evens + '', '4,6,8'
ok evens.join(', ') is '4, 6, 8'
# Backward traversing.
odds = num for num in [0, 1, 2, 3, 4, 5] by -2
eq odds + '', '5,3,1'
# The in operator still works, standalone.
ok 2 of evens
# all/from/to aren't reserved.
all = from = to = 1
# Ensure that the closure wrapper preserves local variables.
obj = {}
@@ -80,7 +64,7 @@ ok i is 3
# Ensure that local variables are closed over for range comprehensions.
funcs = for i in [1..3]
funcs = for i from 1 to 3
-> -i
ok (func() for func in funcs).join(' ') is '-1 -2 -3'
@@ -111,19 +95,14 @@ ok methods[0]() is 'one 0'
ok methods[1]() is 'three 2'
# Naked ranges are expanded into arrays.
array = [0..10]
ok(num % 2 is 0 for num in array by 2)
# Nested comprehensions.
multiLiner =
for x in [3..5]
for y in [3..5]
for x from 3 to 5
for y from 3 to 5
[x, y]
singleLiner =
[x, y] for y in [3..5] for x in [3..5]
[x, y] for y from 3 to 5 for x from 3 to 5
ok multiLiner.length is singleLiner.length
ok 5 is multiLiner[2][2][1]
@@ -159,11 +138,6 @@ ok own.join(' ') is 'Whiskers'
ok all.sort().join(' ') is 'Whiskers cream tabby'
# Optimized range comprehensions.
exxes = 'x' for [0...10]
ok exxes.join(' ') is 'x x x x x x x x x x'
# Comprehensions safely redeclare parameters if they're not present in closest
# scope.
rule = (x) -> x
@@ -173,4 +147,4 @@ learn = ->
ok learn().join(' ') is '1 2 3'
ok rule(101) is 101
ok rule(101) is 101