Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add filter method to Array #429

Merged
merged 2 commits into from
May 23, 2024
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
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