elliotchance / pie

🍕 Enjoy a slice! A utility library for dealing with slices and maps that focuses on type safety and performance.
https://pkg.go.dev/github.com/elliotchance/pie/v2
MIT License
1.96k stars 91 forks source link

Map to return different types #185

Closed mkhstar closed 1 year ago

mkhstar commented 1 year ago

Currently i want to map though a value of one type to another ( eg. some strings and return an integer). Is it possible?

"github.com/elliotchance/pie/v2"

func mapStringToInt(){
  values := []string{"1", "2"}

  results :=  pie.Of(values).Map(func(v string, _ int) int{
    switch(v) {
        case "1":
         return 1
        default:
         return 2
    }
  })
}
// results now becomes []int{1, 2}
elliotchance commented 1 year ago

In it's current form, chaining Map needs to output the same type in as out. Instead you can use the more generic Map:

    results := pie.Map(values, func(v string) int {
        switch v {
        case "1":
            return 1
        default:
            return 2
        }
    })

Perhaps someone want's to put in a PR for generics changes to the chainable Map?

mkhstar commented 1 year ago

Thanks i might open a new pr for that. Thanks for the awesome lib