Sobes.tech
Senior

Practical task: implement a FastestSearcher function that runs tests of multiple search engines in parallel and returns the name of the fastest, response time, and error (if at least one returns an error).

sobes.tech AI

Answer from AI

go package main

import ( "errors" "fmt" "sync" "time" )

type SearchResult struct { Name string Duration time.Duration Err error }

// FastestSearcher runs multiple search functions in parallel and returns the name of the fastest, the time, and an error. func FastestSearcher(searchers map[string]func() error) (string, time.Duration, error) { results := make(chan SearchResult, len(searchers)) var wg sync.WaitGroup

for name, searchFunc := range searchers {
	wg.Add(1)
	go func(n string, f func() error) {
		defer wg.Done()
		start := time.Now()
		err := f()
		dur := time.Since(start)
		results <- SearchResult{Name: n, Duration: dur, Err: err}
	}(name, searchFunc)
}

wg.Wait()
close(results)

var fastest SearchResult
var hasError bool
first := true

for res := range results {
	if res.Err != nil {
		hasError = true
	}
	if first || res.Duration < fastest.Duration {
		fastest = res
		first = false
	}
}

if hasError {
	return fastest.Name, fastest.Duration, errors.New("at least one searcher returned an error")
}
return fastest.Name, fastest.Duration, nil

}

func main() { searchers := map[string]func() error{ "Google": func() error { time.Sleep(100 * time.Millisecond) return nil }, "Bing": func() error { time.Sleep(80 * time.Millisecond) return nil }, "Yahoo": func() error { time.Sleep(120 * time.Millisecond) return errors.New("timeout") }, }

name, duration, err := FastestSearcher(searchers)
fmt.Printf("Fastest: %s, Duration: %v, Error: %v\n", name, duration, err)

}

Practical task: implement a FastestSearcher function… - sobes.tech