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

Filter: an alternative helper that returns both accepted and rejected items #135

Open
samber opened this issue May 17, 2022 · 5 comments
Open

Comments

@samber
Copy link
Owner

samber commented May 17, 2022

Example:

even, odd := lo.FilterXXX[int]([]int{1, 2, 3, 4}, func(x int, _ int) bool {
    return x%2 == 0
})

I would name it lo.Filter2 but it looks weird. Does anyone have a better idea?

A lo.RejectXXX helper would be excellent too.

@CorentinClabaut
Copy link
Contributor

Shouldn't PartitionBy be used in that case?

partitions := lo.PartitionBy[int, int]([]int{1, 2, 3, 4}, func(x int) int {
    return x%2
})

As for the reject isn't it good enough to use lo.Filter with the opposite comparison function?

@samber
Copy link
Owner Author

samber commented Oct 10, 2022

lo.Partition is nice, but not safe: you need to check map values.

Other names:

  • accepted, rejected := FilterReject(...)
  • accepted, rejected := Either(...)

@CorentinClabaut
Copy link
Contributor

That's a good point.

I think I slightly prefer the name Either.

@michaelstoner
Copy link

michaelstoner commented Dec 14, 2023

I found GroupBy helpful when not having an Either implemented yet, and this handles cases when there only one, or 0 results.

grpIsEven := lo.GroupBy[int]([]int{1, 3}, func(x int) bool {
  return x%2 == 0
})
even := grpIsEven[true]
odd := grpIsEven[false]
fmt.Printf("even[%d] odd[%d] even %v odd %v", len(even), len(odd), even, odd)

prints

even[0] odd[2] even [] odd [1 3]

@snamiki1212
Copy link
Contributor

Close this issue. FilterReject has been released: #472

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants