Skip to content

Commit

Permalink
feat: Fix logic in filter_with_previous_loop and add comprehensive …
Browse files Browse the repository at this point in the history
…tests for `filter_with_previous` function
  • Loading branch information
ThatScalaGuy committed Jan 9, 2025
1 parent c828cc4 commit 84a525e
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/gs.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -984,13 +984,14 @@ fn filter_with_previous_loop(
case pred(previous, value) {
True ->
Some(#(value, filter_with_previous_loop(next, Some(value), pred)))
False -> filter_with_previous_loop(next, previous, pred).pull()
False -> filter_with_previous_loop(next, Some(value), pred).pull()
}
}
None -> None
}
})
}

/// Finds the first element in a stream that satisfies a predicate and returns a stream containing only that element.
///
/// ## Example
Expand Down
63 changes: 63 additions & 0 deletions test/gs_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -665,3 +665,66 @@ pub fn bracket_test() {
},
)
}

pub fn filter_with_previous_test() {
// Test basic filtering (keep only increasing values)
gs.from_list([1, 2, 2, 3, 2, 4])
|> gs.filter_with_previous(fn(prev, current) {
case prev {
Some(p) -> current > p
None -> True
}
})
|> gs.to_list
|> should.equal([1, 2, 3, 4])

// Test empty stream
gs.from_empty()
|> gs.filter_with_previous(fn(_, _) { True })
|> gs.to_list
|> should.equal([])
// Test single element (first element always passes with None)
gs.from_pure(42)
|> gs.filter_with_previous(fn(prev, _) {
case prev {
Some(_) -> False
None -> True
}
})
|> gs.to_list
|> should.equal([42])
// Test filtering all elements except first
gs.from_list([1, 2, 3])
|> gs.filter_with_previous(fn(prev, _) {
case prev {
Some(_) -> False
None -> True
}
})
|> gs.to_list
|> should.equal([1])
// Test keeping only duplicates
gs.from_list([1, 1, 2, 2, 2, 3, 4, 4])
|> gs.filter_with_previous(fn(prev, current) {
case prev {
Some(p) -> {
current == p
}

None -> False
}
})
|> gs.to_list
|> should.equal([1, 2, 2, 4])
// Test with take
gs.from_counter(1)
|> gs.filter_with_previous(fn(prev, current) {
case prev {
Some(p) -> current == p + 1
None -> True
}
})
|> gs.take(3)
|> gs.to_list
|> should.equal([1, 2, 3])
}

0 comments on commit 84a525e

Please sign in to comment.