lo
lo copied to clipboard
Proposal: add func like `Map` but with `iteratee` which may return an error
Hi!
I found this package very useful, I wish I find it early.
But I have one small proposal: it may be useful also having one func near lo.Map
which may return an error if conversion fails.
For example we have slice of string
and want to map it to slice of int
.
Right now we must to add extra sugar to catch any errors in current lo.Map
if we don't need it panic.
Just as an example, new function it may look like:
ss := []string{"1", "2", "invalid"}
res, err := lo.MapAmbiguous(ss, strconv.Atoi)
// handle an error
Let me know what you think of it.
What should happen if there is more than 1 error? Should it return the index of the element(s) that caused the error? Should it finish processing the slice after it encounters an error?
I've been finding wanting a feature like this as well. Certain times I've been effectively iterating over a slice of items, effectively doing a map, and bailing from the loop upon the first error.
May I propose a MapWithError
function with the following signature:
func MapWithError[T any, R any](collection []T, iteratee func(item T, index int)) (R, error)) ([]R, error)
If the iteratee
function returns an error for any item being mapped, the function will return a nil slice and the error returned by the iteratee
. Otherwise, the mapped slice will be returned with a nil
error.
I'm happy to contribute this to the project if this sounds good to others.
@lmika this feature seems be implemented by many contributor already. Just waiting for @samber 's approval.
https://github.com/samber/lo/issues/82