Skip to content

How about add a Join function? #298

Description

@donnol

Something like:

package lo

func Join[J, K, R any](
	left []J,
	right []K,
	match func(J, K) bool,
	mapper func(J, K) R,
) []R {
	var r []R

	for _, j := range left {
		for _, k := range right {
			if !match(j, k) {
				continue
			}
			r = append(r, mapper(j, k))
		}
	}

	return r
}

Usage:

type User struct {
	Id   uint64
	Name string
}

type Book struct {
	Id     uint64
	Title  string
	Author uint64 // User.Id
}

type BookWithUser struct {
	Book
	UserName string
}

func UserBookMatcher(j User, k Book) bool {
	return j.Id == k.Author
}

func IntMatcher(j, k int) bool {
	return j == k
}

func main() {
	r := Join([]User{}, []Book{}, UserBookMatcher, func(j User, k Book) BookWithUser {
		return BookWithUser {
			Book: k,
			UserName: j.Name,
		}
	})
	fmt.Println(r)
}

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