OLD | NEW |
| (Empty) |
1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 // Test foreach (aka. for-in) functionality. | |
6 | |
7 testIterator(List expect, Iterable input) { | |
8 int i = 0; | |
9 for (var value in input) { | |
10 Expect.isTrue(i < expect.length); | |
11 Expect.equals(expect[i], value); | |
12 i += 1; | |
13 } | |
14 Expect.equals(expect.length, i); | |
15 | |
16 i = 0; | |
17 var value2; | |
18 for (value2 in input) { | |
19 Expect.isTrue(i < expect.length); | |
20 Expect.equals(expect[i], value2); | |
21 i += 1; | |
22 } | |
23 Expect.equals(expect.length, i); | |
24 } | |
25 | |
26 class MyIterable<T> implements Iterable<T> { | |
27 final List<T> values; | |
28 MyIterable(List<T> values) : this.values = values; | |
29 Iterator iterator() { | |
30 return new MyListIterator(values); | |
31 } | |
32 } | |
33 | |
34 class MyListIterator<T> implements Iterator<T> { | |
35 final List<T> values; | |
36 int index; | |
37 MyListIterator(List<T> values) : this.values = values, index = 0; | |
38 bool hasNext() => index < values.length; | |
39 T next() => values[index++]; | |
40 } | |
41 | |
42 void main() { | |
43 testIterator([], []); | |
44 testIterator([], new MyIterable([])); | |
45 testIterator([1], [1]); | |
46 testIterator([1], new MyIterable([1])); | |
47 testIterator([1,2,3], [1,2,3]); | |
48 testIterator([1,2,3], new MyIterable([1,2,3])); | |
49 testIterator(["a","b","c"], ["a","b","c"]); | |
50 testIterator(["a","b","c"], new MyIterable(["a","b","c"])); | |
51 | |
52 // Several nested for-in's. | |
53 for (var x in [[["a"]]]) { | |
54 for (var y in x) { | |
55 for (var z in y) { | |
56 Expect.equals("a", z); | |
57 } | |
58 } | |
59 } | |
60 | |
61 // Simultaneous iteration of the same iterable. | |
62 for (var iterable in [[1,2,3], new MyIterable([1,2,3])]) { | |
63 int result = 0; | |
64 for (var x in iterable) { | |
65 for (var y in iterable) { | |
66 result += x * y; | |
67 } | |
68 } | |
69 Expect.equals(36, result); | |
70 } | |
71 | |
72 // Using the same variable (showing that the expression is evaluated | |
73 // in the outer scope). | |
74 int result = 0; | |
75 var x = [1,2,3]; | |
76 for (var x in x) { | |
77 result += x; | |
78 } | |
79 Expect.equals(6, result); | |
80 } | |
OLD | NEW |