Skip to content

Commit bbda8c4

Browse files
committed
implement itertools.repeat and itertools.chain
1 parent 1ce27d7 commit bbda8c4

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

graalpython/lib-graalpython/itertools.py

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,48 @@
2222
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
2323
# DEALINGS IN THE SOFTWARE.
2424
class repeat():
25-
pass
25+
def __init__(self, obj, times=None):
26+
self.obj = obj
27+
self.times = times
28+
self.step = 0
29+
30+
def __iter__(self):
31+
return self
32+
33+
def __next__(self):
34+
if self.times is not None:
35+
if self.step >= self.times:
36+
raise StopIteration
37+
else:
38+
self.step += 1
39+
return self.obj
2640

2741

2842
class chain():
29-
pass
43+
"""
44+
Return a chain object whose .__next__() method returns elements from the
45+
first iterable until it is exhausted, then elements from the next
46+
iterable, until all of the iterables are exhausted.
47+
"""
48+
def __init__(self, *iterables):
49+
self._iterables = iterables
50+
self._len = len(iterables)
51+
if self._len > 0:
52+
self._current = iter(self._iterables[0])
53+
self._idx = 0
54+
55+
def __iter__(self):
56+
return self
57+
58+
def __next__(self):
59+
if self._idx >= self._len:
60+
raise StopIteration
61+
try:
62+
return next(self._current)
63+
except (StopIteration, IndexError):
64+
self._idx += 1
65+
self._current = iter(self._iterables[self._idx])
66+
return self.__next__()
3067

3168

3269
class starmap():

0 commit comments

Comments
 (0)