From 1576611661c8923232ce586f1c8b78081dbded9b Mon Sep 17 00:00:00 2001 From: yj-qin Date: Wed, 22 May 2024 22:33:24 +0800 Subject: [PATCH 1/2] add filter method --- array/array_test.mbt | 5 +++++ builtin/array.mbt | 13 +++++++++++++ 2 files changed, 18 insertions(+) diff --git a/array/array_test.mbt b/array/array_test.mbt index 6b16d573..df5ca111 100644 --- a/array/array_test.mbt +++ b/array/array_test.mbt @@ -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())? diff --git a/builtin/array.mbt b/builtin/array.mbt index f6046389..acbd91fa 100644 --- a/builtin/array.mbt +++ b/builtin/array.mbt @@ -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 From 4ec2ef3a2e924089af0ebec2928337e7302863ca Mon Sep 17 00:00:00 2001 From: yj-qin Date: Wed, 22 May 2024 22:44:23 +0800 Subject: [PATCH 2/2] update mbti --- builtin/builtin.mbti | 1 + 1 file changed, 1 insertion(+) diff --git a/builtin/builtin.mbti b/builtin/builtin.mbti index 0a88b112..965dac73 100644 --- a/builtin/builtin.mbti +++ b/builtin/builtin.mbti @@ -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