mirror of
https://github.com/Textualize/textual.git
synced 2025-10-17 02:38:12 +03:00
test for loop_from_index
This commit is contained in:
@@ -46,11 +46,17 @@ def loop_first_last(values: Iterable[T]) -> Iterable[tuple[bool, bool, T]]:
|
||||
|
||||
|
||||
def loop_from_index(
|
||||
values: Sequence[T], index: int, direction: Literal[+1, -1] = +1, wrap: bool = True
|
||||
values: Sequence[T],
|
||||
index: int,
|
||||
direction: Literal[-1, +1] = +1,
|
||||
wrap: bool = True,
|
||||
) -> Iterable[tuple[int, T]]:
|
||||
"""Iterate over values in a sequence from a given starting index, potentially wrapping the index
|
||||
if it would go out of bounds.
|
||||
|
||||
Note that the first value to be yielded is a step from `index`, and `index` will be yielded *last*.
|
||||
|
||||
|
||||
Args:
|
||||
values: A sequence of values.
|
||||
index: Starting index.
|
||||
@@ -60,6 +66,8 @@ def loop_from_index(
|
||||
Yields:
|
||||
A tuple of index and value from the sequence.
|
||||
"""
|
||||
# Sanity check for devs who miss the typing errors
|
||||
assert direction in (-1, +1), "direction must be -1 or +1"
|
||||
count = len(values)
|
||||
if wrap:
|
||||
for _ in range(count):
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from textual._loop import loop_first, loop_first_last, loop_last
|
||||
from textual._loop import loop_first, loop_first_last, loop_from_index, loop_last
|
||||
|
||||
|
||||
def test_loop_first():
|
||||
@@ -26,3 +26,40 @@ def test_loop_first_last():
|
||||
assert next(iterable) == (False, False, "oranges")
|
||||
assert next(iterable) == (False, False, "pears")
|
||||
assert next(iterable) == (False, True, "lemons")
|
||||
|
||||
|
||||
def test_loop_from_index():
|
||||
assert list(loop_from_index("abcdefghij", 3)) == [
|
||||
(4, "e"),
|
||||
(5, "f"),
|
||||
(6, "g"),
|
||||
(7, "h"),
|
||||
(8, "i"),
|
||||
(9, "j"),
|
||||
(0, "a"),
|
||||
(1, "b"),
|
||||
(2, "c"),
|
||||
(3, "d"),
|
||||
]
|
||||
|
||||
assert list(loop_from_index("abcdefghij", 3, direction=-1)) == [
|
||||
(2, "c"),
|
||||
(1, "b"),
|
||||
(0, "a"),
|
||||
(9, "j"),
|
||||
(8, "i"),
|
||||
(7, "h"),
|
||||
(6, "g"),
|
||||
(5, "f"),
|
||||
(4, "e"),
|
||||
(3, "d"),
|
||||
]
|
||||
|
||||
assert list(loop_from_index("abcdefghij", 3, wrap=False)) == [
|
||||
(4, "e"),
|
||||
(5, "f"),
|
||||
(6, "g"),
|
||||
(7, "h"),
|
||||
(8, "i"),
|
||||
(9, "j"),
|
||||
]
|
||||
|
||||
Reference in New Issue
Block a user