Skip to content

Proposal: support error handling on mapping functions (such as slices.Map) #264

@amitlicht

Description

@amitlicht

Usecase: the current implementation of mapping/iterator functions such as map, filter, etc, does not offer error handling. And so if the iteratee function encounters an error case there's no standard way of handling it.

Proposal: extend Map, Filter and similar iterator functions with an error-handling variant of the function, where the iteratee may return an error in which case the iteration breaks and an error is returned from the iterator function.

Example:

// MapErr is similar to lo.Map, but handles error in iteratee function
func MapErr[T any, R any](collection []T, iteratee func(T, int) (R, error)) ([]R, error) {
	result := make([]R, len(collection))

	for i, item := range collection {
		res, err := iteratee(item, i)
		if err != nil {
			return nil, err
		}
		result[i] = res
	}

	return result, nil
}

usage:

package main

import (
	"fmt"
	"github.com/otterize/lox"
	"strings"
)

func main() {
	names, err := lox.MapErr([]string{"Otter", "Other", "Utter"}, func(s string, i int) (string, error) {
		if s == "" {
			return "", fmt.Errorf("empty name")
		}
		return s, nil
	})

	if err != nil {
		panic(err)
	}

	fmt.Printf("Names: %s", strings.Join(names, ","))
}

this example is based on my own implementation at https://github.com/otterize/lox (which I used for my own projects' purpose), and if accepted I'd love to extend it further and suggest it as part of the package.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions