Skip to content

Commit 8ea7d38

Browse files
committed
Add .nth() method to Slice type
1 parent 3d9134b commit 8ea7d38

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/slice.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,48 @@ impl Slice {
4848
pub fn step_by(self, step: Ixs) -> Self {
4949
Slice { step, ..self }
5050
}
51+
52+
/// Returns the `n`th index in this slice.
53+
///
54+
/// The `n` argument starts from zero, so `nth(0)` is the first index. If
55+
/// `n` is greater than or equal to the length of the slice, then the
56+
/// return value is `None`.
57+
///
58+
/// # Examples
59+
///
60+
/// ```
61+
/// use ndarray::Slice;
62+
///
63+
/// // indices 0, 1, 2, 3, 4
64+
/// assert_eq!(Slice::new(0, Some(5), 1).nth(2), Some(2));
65+
///
66+
/// // indices 1, 3
67+
/// assert_eq!(Slice::new(1, Some(5), 2).nth(1), Some(3));
68+
///
69+
/// // indices 1, -1, -3
70+
/// assert_eq!(Slice::new(1, Some(-4), -2).nth(2), Some(-3));
71+
///
72+
/// // indices 1, 3, 5, ...
73+
/// assert_eq!(Slice::new(1, None, 2).nth(2), Some(5));
74+
///
75+
/// // indices 3, 3, 3, ...
76+
/// assert_eq!(Slice::new(3, Some(5), 0).nth(1000), Some(3));
77+
///
78+
/// // indices 1, 3
79+
/// assert_eq!(Slice::new(1, Some(5), 2).nth(2), None);
80+
/// ```
81+
pub fn nth(&self, n: usize) -> Option<isize> {
82+
let nth = self.start + self.step * n as isize;
83+
if let Some(end) = self.end {
84+
if self.step == 0 || (self.step > 0 && nth < end) || (self.step < 0 && nth > end) {
85+
Some(nth)
86+
} else {
87+
None
88+
}
89+
} else {
90+
Some(nth)
91+
}
92+
}
5193
}
5294

5395
impl From<Range<Ixs>> for Slice {

0 commit comments

Comments
 (0)