Skip to content

Commit

Permalink
feat: add find_index interface to array (#558)
Browse files Browse the repository at this point in the history
* feat: add find_index interface to array

* update

* less return

---------

Co-authored-by: Hongbo Zhang <bobzhang1988@gmail.com>
  • Loading branch information
schizobulia and bobzhang committed Jun 18, 2024
1 parent d71590d commit b63c7cd
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
6 changes: 6 additions & 0 deletions array/array_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -441,3 +441,9 @@ test "shuffle" {
let shuffled = Array::shuffle(arr, ~rand)
inspect(shuffled, content="[2, 7, 6, 1, 5, 3, 4]")?
}

test "find_index" {
let arr : Array[Int] = [1, 2, 3, 4, 5, 6, 7]
let index = arr.find_index(fn(x) { x == 3 })
@assertion.assert_eq(index, Some(2))?
}
21 changes: 21 additions & 0 deletions builtin/array.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -955,3 +955,24 @@ pub fn to_string[T : Show](self : Array[T]) -> String {
continue i + 1, "\(init), \(cur)"
}
}

/// Find the index of the first element that satisfies the predicate.
//
/// # Example
///
/// ```
/// let v = [1, 2, 3, 4, 5]
/// match v.find_index(fn(x) { x == 3 }) {
/// Some(index) => println(index) // 2
/// None => println("Not found")
/// }
/// ```
pub fn find_index[T](self : Array[T], f : (T) -> Bool) -> Int? {
for i = 0; i < self.length(); i = i + 1 {
if f(self[i]) {
break Some(i)
}
} else {
None
}
}
1 change: 1 addition & 0 deletions builtin/builtin.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ impl Array {
ends_with[T : Eq](Self[T], Self[T]) -> Bool
extract_if[T](Self[T], (T) -> Bool) -> Self[T]
filter[T](Self[T], (T) -> Bool) -> Self[T]
find_index[T](Self[T], (T) -> Bool) -> Int?
flatten[T](Self[Self[T]]) -> Self[T]
fold_left[T, U](Self[T], (U, T) -> U, ~init : U) -> U
fold_lefti[T, U](Self[T], (Int, U, T) -> U, ~init : U) -> U
Expand Down

0 comments on commit b63c7cd

Please sign in to comment.