blob: 201c2e42209275aaef1a346c4b451473002b40a6 [file] [log] [blame]
Robert Nystrom284f6622019-12-02 23:19:10 +00001// Copyright (c) 2013, 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
5import "package:expect/expect.dart";
6
7main() {
8 void test(expectedList, generatedIterable) {
9 Expect.equals(expectedList.length, generatedIterable.length);
10 Expect.listEquals(expectedList, generatedIterable.toList());
11 }
12
13 test([], new Iterable.generate(0));
14 test([0], new Iterable.generate(1));
15 test([0, 1, 2, 3, 4], new Iterable.generate(5));
16 test(["0", "1", "2", "3", "4"], new Iterable.generate(5, (x) => "$x"));
17 test([2, 3, 4, 5, 6], new Iterable.generate(7).skip(2));
18 test([0, 1, 2, 3, 4], new Iterable.generate(7).take(5));
19 test([], new Iterable.generate(5).skip(6));
20 test([], new Iterable.generate(5).take(0));
21 test([], new Iterable.generate(5).take(3).skip(3));
22 test([], new Iterable.generate(5).skip(6).take(0));
23
24 // Test types.
25
26 Iterable<int> it = new Iterable<int>.generate(5);
27 Expect.isTrue(it is Iterable<int>);
28 Expect.isTrue(it.iterator is Iterator<int>);
29 Expect.isTrue(it is! Iterable<String>);
30 Expect.isTrue(it.iterator is! Iterator<String>);
31 test([0, 1, 2, 3, 4], it);
32
33 Iterable<String> st = new Iterable<String>.generate(5, (x) => "$x");
34 Expect.isTrue(st is Iterable<String>);
35 Expect.isTrue(st.iterator is Iterator<String>);
36 Expect.isFalse(st is Iterable<int>);
37 Expect.isFalse(st.iterator is Iterator<int>);
38 test(["0", "1", "2", "3", "4"], st);
39
40 Expect.throws(() => new Iterable<String>.generate(5));
41
42 // Omitted generator function means `(int x) => x`, and the type parameters
43 // must then be compatible with `int`.
44 // Check that we catch invalid type parameters.
45
46 // Valid types:
47 Iterable<int> iter1 = new Iterable<int>.generate(5);
48 Expect.equals(2, iter1.elementAt(2));
49 Iterable<num> iter2 = new Iterable<num>.generate(5);
50 Expect.equals(2, iter2.elementAt(2));
51 Iterable<Object> iter3 = new Iterable<Object>.generate(5);
52 Expect.equals(2, iter3.elementAt(2));
53 Iterable<dynamic> iter4 = new Iterable<dynamic>.generate(5);
54 Expect.equals(2, iter4.elementAt(2));
55
56 // Invalid types:
57 Expect.throws(() => new Iterable<String>.generate(5));
58 Expect.throws(() => new Iterable<Null>.generate(5).elementAt(2)); //# 01: ok
59 Expect.throws(() => new Iterable<bool>.generate(5));
60
61 // Regression: https://github.com/dart-lang/sdk/issues/26358
62 var count = 0;
63 var iter = new Iterable.generate(5, (v) {
64 count++;
65 return v;
66 });
67 Expect.equals(0, count);
68 Expect.equals(2, iter.elementAt(2)); // Doesn't compute the earlier values.
69 Expect.equals(1, count);
70 Expect.equals(2, iter.skip(2).first); // Doesn't compute the skipped values.
71 Expect.equals(2, count);
72}