Avoid Loop Labels by Using an Anonymous Func #21

Open
opened 2021-03-22 02:23:24 +00:00 by jeff · 0 comments
Owner

Contrived example:

package main

type state struct {
	counties []county
}

type county struct {
	towns []town
}

type town struct {
	people []string
}

func main() {
	s := state{
		counties: []county{
			{
				towns: []town{
					{
						people: []string{"tony", "tom", "mike"},
					},
					{
						people: []string{"kelly", "sara", "tony"},
					},
				},
			},
			{
				towns: []town{
					{
						people: []string{"tony", "amanda"},
					},
					{
						people: []string{"john", "katie", "tony"},
					},
				},
			},
		},
	}

	_ = allTownsContainPerson(s, "tony")
	_ = allTownsContainPersonWithFunc(s, "tony")
}

func allTownsContainPerson(s state, person string) bool {
	for _, c := range s.counties {
	townLevel:
		for _, t := range c.towns {
			for _, p := range t.people {
				if p == person {
					// This town has the person, so no need to check remaining population
					continue townLevel
				}
			}
		}
	}

	return false
}

func allTownsContainPersonWithFunc(s state, person string) bool {
	townContainsPerson := func (t town, person string) bool {
		for _, p := range t.people {
			if p == person {
				return true
			}
		}
		
		return false
	}

	for _, c := range s.counties {
		for _, t := range c.towns {
			if !townContainsPerson(t, person) {
				return false
			}
		}
	}

	return true
}


Contrived example: ```go package main type state struct { counties []county } type county struct { towns []town } type town struct { people []string } func main() { s := state{ counties: []county{ { towns: []town{ { people: []string{"tony", "tom", "mike"}, }, { people: []string{"kelly", "sara", "tony"}, }, }, }, { towns: []town{ { people: []string{"tony", "amanda"}, }, { people: []string{"john", "katie", "tony"}, }, }, }, }, } _ = allTownsContainPerson(s, "tony") _ = allTownsContainPersonWithFunc(s, "tony") } func allTownsContainPerson(s state, person string) bool { for _, c := range s.counties { townLevel: for _, t := range c.towns { for _, p := range t.people { if p == person { // This town has the person, so no need to check remaining population continue townLevel } } } } return false } func allTownsContainPersonWithFunc(s state, person string) bool { townContainsPerson := func (t town, person string) bool { for _, p := range t.people { if p == person { return true } } return false } for _, c := range s.counties { for _, t := range c.towns { if !townContainsPerson(t, person) { return false } } } return true } ```
Sign in to join this conversation.
No Milestone
No Assignees
1 Participants
Notifications
Due Date
The due date is invalid or out of range. Please use the format 'yyyy-mm-dd'.

No due date set.

Dependencies

No dependencies set.

Reference: simplesystems/go-resources#21
No description provided.