github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/fsm/test/example.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "time" 6 ) 7 8 type ElectricCircuit struct { 9 Description string 10 Connected bool 11 } 12 13 type Light struct { 14 Room string 15 HasBulb bool 16 } 17 18 type Plumbing struct { 19 Location string 20 NumberOfLeaks uint 21 } 22 23 type House struct { 24 Address string 25 Area uint 26 ElectricCircuits []*ElectricCircuit 27 Lights []*Light 28 PlumbingSystems []*Plumbing 29 } 30 31 func (circuit *ElectricCircuit) NeedsRepairs() bool { 32 time.Sleep(1 * time.Microsecond) 33 return !circuit.Connected 34 } 35 36 func (light *Light) NeedsRepairs() bool { 37 time.Sleep(1 * time.Microsecond) 38 return !light.HasBulb 39 } 40 41 func (plumbing *Plumbing) NeedsRepairs() bool { 42 time.Sleep(1 * time.Microsecond) 43 return plumbing.NumberOfLeaks > 0 44 } 45 46 func (house *House) NeedsRepairs() bool { 47 for _, circuit := range house.ElectricCircuits { 48 if circuit.NeedsRepairs() { 49 return true 50 } 51 } 52 53 for _, light := range house.Lights { 54 if light.NeedsRepairs() { 55 return true 56 } 57 } 58 59 for _, plumbing := range house.PlumbingSystems { 60 if plumbing.NeedsRepairs() { 61 return true 62 } 63 } 64 65 return false 66 } 67 68 func HugeHouse() *House { 69 h := &House{ 70 Address: "123 Fake Street", 71 Area: 999, 72 } 73 for i := 0; i < 1e6; i += 1 { 74 h.ElectricCircuits = append(h.ElectricCircuits, &ElectricCircuit{"Main", true}) 75 } 76 for i := 0; i < 1e6/2; i += 1 { 77 h.Lights = append(h.Lights, &Light{"Kitchen", true}, &Light{"Dining", true}) 78 } 79 for i := 0; i < 1e6; i += 1 { 80 h.PlumbingSystems = append(h.PlumbingSystems, &Plumbing{"Bathroom", 0}) 81 } 82 return h 83 } 84 85 func main() { 86 house := HugeHouse() 87 start := time.Now() 88 if house.NeedsRepairs() { 89 fmt.Println("Fix-it! Fix-it! Fix-it!") 90 } else { 91 fmt.Println("All good.") 92 } 93 fmt.Println(time.Since(start)) 94 }