Skip to content

Commit

Permalink
feat: more commands (#109)
Browse files Browse the repository at this point in the history
  • Loading branch information
MartinBernstorff authored Feb 10, 2024
2 parents b198785 + 97c23fa commit e375bbd
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
14 changes: 13 additions & 1 deletion iterpy/iter.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def __getitem__(self, index: int | slice) -> T | "Iter[T]":
)

def __repr__(self) -> str:
return f"Iter({self._nonconsumable_iterable})"
return f"Iter{self._nonconsumable_iterable}"

def __eq__(self, other: object) -> bool:
if not isinstance(other, Iter):
Expand Down Expand Up @@ -154,3 +154,15 @@ def unique_by(self, func: Callable[[T], S]) -> "Iter[T]":
values.append(value)

return Iter(values)

def enumerate(self) -> "Iter[tuple[int, T]]":
return Iter(enumerate(self._iterator))

def find(self, func: Callable[[T], bool]) -> T | None:
for value in self._iterator:
if func(value):
return value
return None

def last(self) -> T:
return self._nonconsumable_iterable[-1]
4 changes: 4 additions & 0 deletions iterpy/iter.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ class Iter(Generic[T]):
def all(self, func: Callable[[T], bool]) -> bool: ...
def unique(self) -> Iter[T]: ...
def unique_by(self, func: Callable[[T], U]) -> Iter[T]: ...
def enumerate(self) -> Iter[tuple[int, T]]: ...
def find(self, func: Callable[[T], bool]) -> T: ...
def last(self) -> T: ...
def sum(self) -> T: ...
def groupby(
self, func: Callable[[T], str]
) -> Iter[tuple[str, list[T]]]: ...
Expand Down
20 changes: 20 additions & 0 deletions iterpy/test_iter.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,26 @@ def test_unique_by():
]


def test_enumerate():
test_iterator = Iter([1, 2, 3])
assert test_iterator.enumerate().to_list() == [
(0, 1),
(1, 2),
(2, 3),
]


def test_find():
test_iterator = Iter([1, 2, 3])
assert test_iterator.find(lambda x: x == 2) == 2
assert test_iterator.find(lambda x: x == 4) is None


def test_last():
test_iterator = Iter([1, 2, 3])
assert test_iterator.last() == 3


def test_flatten():
test_input: list[list[int]] = [[1, 2], [3, 4]]
iterator = Iter(test_input)
Expand Down

0 comments on commit e375bbd

Please sign in to comment.