Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Changelog
Unreleased
----------

- Support ``range`` objects in ``index_of``, including when a start index is supplied.
- Merge nested mutable mappings in place instead of replacing their existing contents, including
``UserDict`` and ``ChainMap``, and apply deep defaults and customizers to their entries.
- Allow sort directions in ``order_by`` to be iterables without a truth value.
Expand Down
12 changes: 12 additions & 0 deletions src/pydash/arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -799,6 +799,18 @@ def index_of(array: t.Sequence[T], value: T, from_index: int = 0) -> int:
.. versionadded:: 1.0.0
"""
if isinstance(array, range):
# range.index does not accept a starting index. Slicing preserves
# range's arithmetic search without materializing the sequence.
tail = array[from_index:]
# At runtime range.index also accepts objects that compare equal to an int.
searchable_tail: Sequence[object] = tail
try:
index = searchable_tail.index(value)
except ValueError:
return -1
return array.index(tail.start) + index

try:
return array.index(value, from_index)
except ValueError:
Expand Down
20 changes: 20 additions & 0 deletions tests/test_arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,26 @@ def test_index_of(case, value, from_index, expected):
assert _.index_of(case, value, from_index) == expected


@parametrize(
"sequence,value,start,expected",
[
(range(10, 20, 2), 14, 0, 2),
(range(10, 20, 2), 14, 3, -1),
(range(10, 20, 2), 14, -3, 2),
(range(10, 20, 2), 14, -2, -1),
(range(10, 20, 2), 14, -100, 2),
(range(20, 10, -2), 14, 2, 3),
(range(10, 20, 2), 14, 100, -1),
(range(10, 20, 2), 15, 0, -1),
(range(10, 20, 2), 14.0, 0, 2),
(range(0), 0, 0, -1),
(range(10**30), 10**30 - 1, -2, 10**30 - 1),
],
)
def test_index_of_range(sequence, value, start, expected):
assert _.index_of(sequence, value, start) == expected


@parametrize("case,expected", [([1, 2, 3], [1, 2]), ([1], [])])
def test_initial(case, expected):
assert _.initial(case) == expected
Expand Down