Skip to content

Commit 0beed29

Browse files
committed
add textiter module with head and tail functions
1 parent 2fa2288 commit 0beed29

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

lib/fdiff/textiter.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from collections import deque
2+
from itertools import islice
3+
4+
5+
def head(iterable, n):
6+
"""Returns the first n indices of `iterable` as an iterable."""
7+
return islice(iterable, n)
8+
9+
10+
def tail(iterable, n):
11+
"""Returns the last n indices of `iterable` as an iterable."""
12+
return iter(deque(iterable, maxlen=n))

tests/test_textiter.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
2+
3+
import pytest
4+
5+
from fdiff.textiter import head, tail
6+
7+
text_list = [
8+
"line 1",
9+
"line 2",
10+
"line 3",
11+
"line 4",
12+
"line 5"
13+
]
14+
15+
16+
def test_head():
17+
head_res = head(text_list, 2)
18+
assert len(list(head_res)) == 2
19+
for x, line in enumerate(head_res):
20+
assert line == text_list[x]
21+
22+
23+
def test_head_request_more_than_available():
24+
head_res = head(text_list, 6)
25+
assert len(list(head_res)) == 5
26+
for x, line in enumerate(head_res):
27+
assert line == text_list[x]
28+
29+
30+
def test_tail():
31+
tail_res = tail(text_list, 2)
32+
assert len(list(tail_res)) == 2
33+
offset = 3
34+
for x, line in enumerate(tail_res):
35+
assert line == text_list[offset + x]
36+
37+
38+
def test_tail_request_more_than_available():
39+
tail_res = tail(text_list, 6)
40+
assert len(list(tail_res)) == 5
41+
for x, line in enumerate(tail_res):
42+
assert line == text_list[x]

0 commit comments

Comments
 (0)