1
+ /**
2
+ * Copyright 2013 Netflix, Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ package rx .util ;
17
+
18
+ import org .junit .Test ;
19
+
20
+ import java .util .*;
21
+
22
+ import static org .junit .Assert .assertEquals ;
23
+
24
+ public final class Range implements Iterable <Integer > {
25
+ private final int start ;
26
+ private final int end ;
27
+ private final int step ;
28
+
29
+ public static Range createWithCount (int start , int count ) {
30
+ return create (start , start * (count + 1 ));
31
+ }
32
+
33
+ public static Range create (int start , int end ) {
34
+ return new Range (start , end , 1 );
35
+ }
36
+
37
+ public static Range createWithStep (int start , int end , int step ) {
38
+ return new Range (start , end , step );
39
+ }
40
+
41
+ private Range (int start , int end , int step ) {
42
+ this .start = start ;
43
+ this .end = end ;
44
+ this .step = step ;
45
+ }
46
+
47
+ @ Override
48
+ public Iterator <Integer > iterator () {
49
+ return new Iterator <Integer >() {
50
+ private int current = start ;
51
+
52
+ @ Override
53
+ public boolean hasNext () {
54
+ return current < end ;
55
+ }
56
+
57
+ @ Override
58
+ public Integer next () {
59
+ if (!hasNext ()) {
60
+ throw new NoSuchElementException ("No more elements" );
61
+ }
62
+ int result = current ;
63
+ current += step ;
64
+ return result ;
65
+ }
66
+
67
+ @ Override
68
+ public void remove () {
69
+ throw new UnsupportedOperationException ("Read only iterator" );
70
+ }
71
+ };
72
+ }
73
+
74
+ @ Override
75
+ public String toString () {
76
+ return "Range (" + start + ", " + end + "), step " + step ;
77
+ }
78
+
79
+
80
+ public static class UnitTest {
81
+
82
+ @ Test
83
+ public void testSimpleRange () {
84
+ assertEquals (Arrays .asList (1 , 2 , 3 , 4 ), toList (Range .create (1 , 5 )));
85
+ }
86
+
87
+ @ Test
88
+ public void testRangeWithStep () {
89
+ assertEquals (Arrays .asList (1 , 3 , 5 , 7 , 9 ), toList (Range .createWithStep (1 , 10 , 2 )));
90
+ }
91
+
92
+ @ Test
93
+ public void testRangeWithCount () {
94
+ assertEquals (Arrays .asList (1 , 2 , 3 , 4 , 5 ), toList (Range .createWithCount (1 , 5 )));
95
+ }
96
+
97
+
98
+ private static <T > List <T > toList (Iterable <T > iterable ) {
99
+ List <T > result = new ArrayList <T >();
100
+ for (T element : iterable ) {
101
+ result .add (element );
102
+ }
103
+ return result ;
104
+ }
105
+
106
+ }
107
+ }
0 commit comments