Skip to content

Commit

Permalink
Merge pull request #429 from yj-qin/array-filter
Browse files Browse the repository at this point in the history
Add filter method to Array
  • Loading branch information
bobzhang committed May 23, 2024
2 parents 8f150b8 + 4ec2ef3 commit 74ebec2
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
5 changes: 5 additions & 0 deletions array/array_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,11 @@ test "mapi_inplace" {
inspect(e, content="[]")?
}

test "filter" {
let arr = [1, 2, 3, 4, 5, 6]
inspect(arr.filter(fn(x) { x % 2 == 0 }), content="[2, 4, 6]")?
}

test "is_empty" {
let v = Array::new()
@assertion.assert_true(v.is_empty())?
Expand Down
13 changes: 13 additions & 0 deletions builtin/array.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,19 @@ pub fn mapi_inplace[T](self : Array[T], f : (Int, T) -> T) -> Unit {
}
}

/// Filters the array with a predicate function.
///
/// # Example
/// ```
/// let arr = [1, 2, 3, 4, 5, 6]
/// arr.filter(fn (x) { x % 2 == 0 }) // [2, 4, 6]
/// ```
pub fn filter[T](self : Array[T], f : (T) -> Bool) -> Array[T] {
let arr = []
self.iter(fn(e) { if f(e) { arr.push(e) } })
arr
}

/// Test if the vector is empty.
///
/// # Example
Expand Down
1 change: 1 addition & 0 deletions builtin/builtin.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ impl Array {
extract_if[T](Self[T], (T) -> Bool) -> Self[T]
fill[T](Self[T], T) -> Unit
fill_with[T](Self[T], () -> T) -> Unit
filter[T](Self[T], (T) -> Bool) -> Self[T]
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 74ebec2

Please sign in to comment.